jueves, 30 de enero de 2014

Drivers HP Pavilion g7-2022us Notebook PC support

PC Notebook HP Pavilion g7-1105ss Controladores

PC Notebook HP Pavilion g7-1105ss soporte


PC Notebook HP Pavilion g7-1105ss Controladores

Verificar actualizaciones

Escanear su sistema para buscar controladores y software desactualizados o no encontrados.
Explorar ahora
O

Seleccionar el sistema operativo

Microsoft Windows 7 (64-bit)

Seleccione una descarga a continuación

Mostrar todoOcultar todo



Adaptador WiFi 802.11 b/g/n Ralink
2012-06-06 , Versión3.2.13.0, 22.39M(‏Versiones anteriores disponibles)‏
Este paquete contiene el paquete de instalación de controladores para el controlador LAN inalámbrica Ralink en los modelos de notebook admitidos que ejecutan un sistema operativo admitido.   (Más detalles)
Al efectuar la descarga, usted se compromete a aceptar los términos de uso de HP  Términos de uso

Controlador de LAN inalámbrica 802.11b/g/n Realtek RTL8188CE para Microsoft Windows
2012-04-17 , Versión1005.33.313.2012, 19.49M
Este paquete contiene el paquete de instalación del controlador para la controladora de LAN inalámbrica Realtek RTL8188CE en los modelos de notebook admitidos que ejecutan un sistema operativo ...   (Más detalles)
Al efectuar la descarga, usted se compromete a aceptar los términos de uso de HP  Términos de uso

Controlador de red de área local (LAN) Realtek
2011-11-18 , Versión7.40.126.2011, 5.72M
Este paquete proporciona el controlador de red de área local (LAN) Realtek que habilita el chip de la tarjeta de interfaz de red (NIC) Realtek en los modelos de notebook admitidos que cuentan con un ...   (Más detalles)
Al efectuar la descarga, usted se compromete a aceptar los términos de uso de HP  Términos de uso

Controlador para el adaptador Ralink/Motorola Bluetooth
2011-11-04 , Versión3.0.43.307, 48.68M(‏Versiones anteriores disponibles)‏
Este paquete contiene el paquete de instalación del controlador para el Adaptador Ralink/Motorola Bluetooth y Alta Velocidad (HS) en los modelos de notebook y sistemas operativos admitidos.   (Más detalles)
Al efectuar la descarga, usted se compromete a aceptar los términos de uso de HP  Términos de uso

Controlador de LAN inalámbrica Realtek RTL8188CE 802.11b/g/n para Microsoft Windows
2011-06-30 , Versión1005.22.615.2011, 23.05M(‏Versiones anteriores disponibles)‏
Este paquete contiene el paquete de instalación del controlador para la controladora de LAN inalámbrica Realtek RTL8188CE en los modelos de notebooks y sistemas operativos admitidos.   (Más detalles)
Al efectuar la descarga, usted se compromete a aceptar los términos de uso de HP  Términos de uso

Controlador de LAN inalámbrica Atheros para Microsoft Windows 7
2011-05-24 , Versión9.20, 81.98M(‏Versiones anteriores disponibles)‏
Este paquete contiene controladores para los adaptadores de LAN inalámbrica Atheros compatibles con los modelos de notebook/laptop y sistemas operativos admitidos. NOTA: Para ver una lista de ...   (Más detalles)
Al efectuar la descarga, usted se compromete a aceptar los términos de uso de HP  Términos de uso

Controlador de Bluetooth Atheros
2011-05-17 , Versión7.2, 307.38M(‏Versiones anteriores disponibles)‏
Este paquete contiene el paquete de instalación del controlador de Bluetooth Atheros presente en los modelos de notebook y los sistemas operativos compatibles.   (Más detalles)
Al efectuar la descarga, usted se compromete a aceptar los términos de uso de HP  Términos de uso

Controlador de red de área local (LAN) Realtek
2011-05-06 , Versión7.34.1130.2010, 5.72M
Este paquete proporciona el controlador de red de área local (LAN) Realtek que habilita el chip de la tarjeta de interfaz de red (NIC) Realtek en los modelos de notebook admitidos que cuentan con un ...   (Más detalles)
Al efectuar la descarga, usted se compromete a aceptar los términos de uso de HP  Términos de uso

Controlador Realtek Motorola BC8 Bluetooth 3.0+HS para Microsoft Windows
2011-03-14 , Versión3.0.82.298, 49.39M
Este paquete contiene los archivos de instalación del controlador de bluetooth Realtek y Motorola para los modelos de notebook y los sistemas operativos admitidos.   (Más detalles)
Al efectuar la descarga, usted se compromete a aceptar los términos de uso de HP  Términos de uso

Controlador de LAN inalámbrica Broadcom para Microsoft Windows 7
2011-01-20 , Versión5.60.350.23, 43.62M
Este paquete contiene los controladores de LAN inalámbrica Broadcom necesarios para habilitar el adaptador de LAN inalámbrica Broadcom integrado en los modelos de notebook con los sistemas operativos ...   (Más detalles)
Al efectuar la descarga, usted se compromete a aceptar los términos de uso de HP  Términos de uso












lunes, 27 de enero de 2014

Tipos de Datos PostgresSql

Chapter 8. Data Types

PostgreSQL has a rich set of native data types available to users. Users may add new types to PostgreSQL using the CREATE TYPE command.
Table 8-1 shows all built-in general-purpose data types. Most of the alternative names listed in the "Aliases" column are the names used internally by PostgreSQL for historical reasons. In addition, some internally used or deprecated types are available, but they are not listed here.
Table 8-1. Data Types
Name Aliases Description
bigint int8 signed eight-byte integer
bigserial serial8 autoincrementing eight-byte integer
bit   fixed-length bit string
bit varying(n) varbit(n) variable-length bit string
boolean bool logical Boolean (true/false)
box   rectangular box in the plane
bytea   binary data
character varying(n) varchar(n) variable-length character string
character(n) char(n) fixed-length character string
cidr   IPv4 or IPv6 network address
circle   circle in the plane
date   calendar date (year, month, day)
double precision float8 double precision floating-point number
inet   IPv4 or IPv6 host address
integer int, int4 signed four-byte integer
interval(p)   time span
line   infinite line in the plane (not fully implemented)
lseg   line segment in the plane
macaddr   MAC address
money   currency amount
numeric [ (p, s) ] decimal [ (p, s) ] exact numeric with selectable precision
path   open and closed geometric path in the plane
point   geometric point in the plane
polygon   closed geometric path in the plane
real float4 single precision floating-point number
smallint int2 signed two-byte integer
serial serial4 autoincrementing four-byte integer
text   variable-length character string
time [ (p) ] [ without time zone ]   time of day
time [ (p) ] with time zone timetz time of day, including time zone
timestamp [ (p) ] [ without time zone ] timestamp date and time
timestamp [ (p) ] with time zone timestamptz date and time, including time zone
Compatibility: The following types (or spellings thereof) are specified by SQL: bit, bit varying, boolean, char, character varying, character, varchar, date, double precision, integer, interval, numeric, decimal, real, smallint, time (with or without time zone), timestamp (with or without time zone).
Each data type has an external representation determined by its input and output functions. Many of the built-in types have obvious external formats. However, several types are either unique to PostgreSQL, such as open and closed paths, or have several possibilities for formats, such as the date and time types. Some of the input and output functions are not invertible. That is, the result of an output function may lose accuracy when compared to the original input.
Some of the operators and functions (e.g., addition and multiplication) do not perform run-time error-checking in the interests of improving execution speed. On some systems, for example, the numeric operators for some data types may silently cause underflow or overflow.

8.1. Numeric Types

Numeric types consist of two-, four-, and eight-byte integers, four- and eight-byte floating-point numbers, and fixed-precision decimals. Table 8-2 lists the available types.
Table 8-2. Numeric Types
Name Storage Size Description Range
smallint 2 bytes small-range integer -32768 to +32767
integer 4 bytes usual choice for integer -2147483648 to +2147483647
bigint 8 bytes large-range integer -9223372036854775808 to 9223372036854775807
decimal variable user-specified precision, exact no limit
numeric variable user-specified precision, exact no limit
real 4 bytes variable-precision, inexact 6 decimal digits precision
double precision 8 bytes variable-precision, inexact 15 decimal digits precision
serial 4 bytes autoincrementing integer 1 to 2147483647
bigserial 8 bytes large autoincrementing integer 1 to 9223372036854775807
The syntax of constants for the numeric types is described in Section 4.1.2. The numeric types have a full set of corresponding arithmetic operators and functions. Refer to Chapter 9 for more information. The following sections describe the types in detail.

8.1.1. Integer Types

The types smallint, integer, and bigint store whole numbers, that is, numbers without fractional components, of various ranges. Attempts to store values outside of the allowed range will result in an error.
The type integer is the usual choice, as it offers the best balance between range, storage size, and performance. The smallint type is generally only used if disk space is at a premium. The bigint type should only be used if the integer range is not sufficient, because the latter is definitely faster.
The bigint type may not function correctly on all platforms, since it relies on compiler support for eight-byte integers. On a machine without such support, bigint acts the same as integer (but still takes up eight bytes of storage). However, we are not aware of any reasonable platform where this is actually the case.
SQL only specifies the integer types integer (or int) and smallint. The type bigint, and the type names int2, int4, and int8 are extensions, which are shared with various other SQL database systems.
Note: If you have a column of type smallint or bigint with an index, you may encounter problems getting the system to use that index. For instance, a clause of the form
... WHERE smallint_column = 42
will not use an index, because the system assigns type integer to the constant 42, and PostgreSQL currently cannot use an index when two different data types are involved. A workaround is to single-quote the constant, thus:
... WHERE smallint_column = '42'
This will cause the system to delay type resolution and will assign the right type to the constant.

8.1.2. Arbitrary Precision Numbers

The type numeric can store numbers with up to 1000 digits of precision and perform calculations exactly. It is especially recommended for storing monetary amounts and other quantities where exactness is required. However, the numeric type is very slow compared to the floating-point types described in the next section.
In what follows we use these terms: The scale of a numeric is the count of decimal digits in the fractional part, to the right of the decimal point. The precision of a numeric is the total count of significant digits in the whole number, that is, the number of digits to both sides of the decimal point. So the number 23.5141 has a precision of 6 and a scale of 4. Integers can be considered to have a scale of zero.
Both the precision and the scale of the numeric type can be configured. To declare a column of type numeric use the syntax
NUMERIC(precision, scale)
The precision must be positive, the scale zero or positive. Alternatively,
NUMERIC(precision)
selects a scale of 0. Specifying
NUMERIC
without any precision or scale creates a column in which numeric values of any precision and scale can be stored, up to the implementation limit on precision. A column of this kind will not coerce input values to any particular scale, whereas numeric columns with a declared scale will coerce input values to that scale. (The SQL standard requires a default scale of 0, i.e., coercion to integer precision. We find this a bit useless. If you're concerned about portability, always specify the precision and scale explicitly.)
If the precision or scale of a value is greater than the declared precision or scale of a column, the system will attempt to round the value. If the value cannot be rounded so as to satisfy the declared limits, an error is raised.
The types decimal and numeric are equivalent. Both types are part of the SQL standard.

8.1.3. Floating-Point Types

The data types real and double precision are inexact, variable-precision numeric types. In practice, these types are usually implementations of IEEE Standard 754 for Binary Floating-Point Arithmetic (single and double precision, respectively), to the extent that the underlying processor, operating system, and compiler support it.
Inexact means that some values cannot be converted exactly to the internal format and are stored as approximations, so that storing and printing back out a value may show slight discrepancies. Managing these errors and how they propagate through calculations is the subject of an entire branch of mathematics and computer science and will not be discussed further here, except for the following points:
  • If you require exact storage and calculations (such as for monetary amounts), use the numeric type instead.
  • If you want to do complicated calculations with these types for anything important, especially if you rely on certain behavior in boundary cases (infinity, underflow), you should evaluate the implementation carefully.
  • Comparing two floating-point values for equality may or may not work as expected.
On most platforms, the real type has a range of at least 1E-37 to 1E+37 with a precision of at least 6 decimal digits. The double precision type typically has a range of around 1E-307 to 1E+308 with a precision of at least 15 digits. Values that are too large or too small will cause an error. Rounding may take place if the precision of an input number is too high. Numbers too close to zero that are not representable as distinct from zero will cause an underflow error.
PostgreSQL also supports the SQL-standard notations float and float(p) for specifying inexact numeric types. Here, p specifies the minimum acceptable precision in binary digits. PostgreSQL accepts float(1) to float(24) as selecting the real type, while float(25) to float(53) select double precision. Values of p outside the allowed range draw an error. float with no precision specified is taken to mean double precision.
Note: Prior to PostgreSQL 7.4, the precision in float(p) was taken to mean so many decimal digits. This has been corrected to match the SQL standard, which specifies that the precision is measured in binary digits. The assumption that real and double precision have exactly 24 and 53 bits in the mantissa respectively is correct for IEEE-standard floating point implementations. On non-IEEE platforms it may be off a little, but for simplicity the same ranges of p are used on all platforms.

8.1.4. Serial Types

The data types serial and bigserial are not true types, but merely a notational convenience for setting up unique identifier columns (similar to the AUTO_INCREMENT property supported by some other databases). In the current implementation, specifying
CREATE TABLE tablename (
    colname SERIAL
);
is equivalent to specifying:
CREATE SEQUENCE tablename_colname_seq;
CREATE TABLE tablename (
    colname integer DEFAULT nextval('tablename_colname_seq') NOT NULL
);
Thus, we have created an integer column and arranged for its default values to be assigned from a sequence generator. A NOT NULL constraint is applied to ensure that a null value cannot be explicitly inserted, either. In most cases you would also want to attach a UNIQUE or PRIMARY KEY constraint to prevent duplicate values from being inserted by accident, but this is not automatic.
Note: Prior to PostgreSQL 7.3, serial implied UNIQUE. This is no longer automatic. If you wish a serial column to be in a unique constraint or a primary key, it must now be specified, same as with any other data type.
To insert the next value of the sequence into the serial column, specify that the serial column should be assigned its default value. This can be done either by excluding the column from the list of columns in the INSERT statement, or through the use of the DEFAULT key word.
The type names serial and serial4 are equivalent: both create integer columns. The type names bigserial and serial8 work just the same way, except that they create a bigint column. bigserial should be used if you anticipate the use of more than 231 identifiers over the lifetime of the table.
The sequence created for a serial column is automatically dropped when the owning column is dropped, and cannot be dropped otherwise. (This was not true in PostgreSQL releases before 7.3. Note that this automatic drop linkage will not occur for a sequence created by reloading a dump from a pre-7.3 database; the dump file does not contain the information needed to establish the dependency link.) Furthermore, this dependency between sequence and column is made only for the serial column itself; if any other columns reference the sequence (perhaps by manually calling the nextval function), they will be broken if the sequence is removed. Using a serial column's sequence in such a fashion is considered bad form; if you wish to feed several columns from the same sequence generator, create the sequence as an independent object.

domingo, 26 de enero de 2014

MySQL - CREATE USER with GRANT Privileges in Terminal

Reglas y Permisos Postgres SQL

Reglas y permisos

Debido a la reescritura de las queries por el sistema de reglas de Postgre, se han accedido a otras tablas/vistas diferentes de las de la query original. Utilizando las reglas de update, esto puede incluir acceso en escritura a tablas.
Las reglas de reescritura no tienen un propietario diferenciado. El propietario de una relación (tabla o vista) es automáticamente el propietario de las reglas de reescritura definidas para ella. El sistema de reglas de Postgres cambia el comportamiento del sistema de control de acceso de defecto. Las relaciones que se utilizan debido a las reglas son comprobadas durante la reescritura contralos permisos del propietario de la relación, contra la que la regla se ha definido. Esto hace que el usuario no necesite sólo permisos para las tablas/vistas a las que él hace referencia en sus queries.
Por ejemplo: Un usuario tiene una lista de números de teléfono en la que algunos son privados y otros son de interés para la secretaria en la oficina. Él puede construir lo siguiente:
    CREATE TABLE phone_data (person text, phone text, private bool);
    CREATE VIEW phone_number AS
        SELECT person, phone FROM phone_data WHERE NOT private;
    GRANT SELECT ON phone_number TO secretary;
Nadie excepto él, y el superusuario de la base de datos, pueden acceder a la tabla phone_data. Pero debido a la GRANT, la secretaria puede SELECT a través de la vista phone_numbre. El sistema de reglas reescribirá la SELECT de phone_numbre en una SELECT de phone_data y añade la cualificación de que sólo se buscan las entradas cuyo "privado" sea falso. Una vez que el usuario sea el propietario de phone_numbre, la lectura accede a phone_data se comprueba contra sus permisos, y la query se considera autorizada. La comprobación para acceder a phone_number se realiza entonces, de modo que nadie más que la secretaria pueda utilizarlo. Los permisos son comprobados regla a regla. De modo que la secretaria es ahora la única que puede ver los números de teléfono públicos. Pero la secretaria puede crear otra vista y autorizar el acceso a ella al público. Entonces, cualquiera puede ver los datos de phone_numbre a través de la vista de la secretaria. Lo que la secretaria no puede hacer es crear una vista que acceda directamente a phone_data (realmente si puede, pero no trabajará, puesto que cada acceso abortará la transacción durante la comprobación de los permisos). Y tan pronto como el usuario tenga noticia de que la secretaria ha abierto su vista a phone_numbre, el puede REVOKE su acceso. Inmediatamente después, cualquier acceso a la vista de las secretarias fallará.
Alguien podría pensar que este chequeo regla a regla es un agujero de seguridad, pero de hecho no lo es. Si esto no trabajase, la secretaria podría generar una tabla con las mismas columnas de phone_number y copiar los datos aquí todos los días. En este caso serían ya sus propios datos, y podría autorizar el acceso a cualquiera que ella quisiera. Un GRANT quiere decir "Yo Confío en Tí". Si alguien en quien confiamos hace lo anterior, es el momento de volver sobre nuestros pasos, y hacer el REVOKE.
Este mecanismo también trabaja para reglas de update. En el ejemplo de la sección previa, el propietario de las tablas de la base de datos de Al (suponiendo que no fuera el mismo Al) podría haber autorizado (GRANT) SELECT, INSERT, UPDATE o DELETE a la vista shoelace a Al. Pero sólo SELECT en shoelace_log. La acción de la regla de escribir entradas del log deberá ser ejecutada con exito, y Al podría ver las entradas del log, pero el no puede crear nuevas entradas, ni podría manipular ni remover las existentes.
NotaAtención
  GRANT ALL actualmente incluye permisos RULE. Esto permite al usuario autorizado borrar la regla, hacer los cambios y reinstalarla. Pienso que esto debería ser cambiado rápidamente.

15 PostgreSQL tuts VIEWS Usage

Instalacion SQL Server 2008

sábado, 25 de enero de 2014

Comandos para Postgres

PostgreSQL es un servidor de base de datos objeto relacional libre, liberado bajo la licencia BSD. Como muchos otros proyectos open source, el desarrollo de PostgreSQL no es manejado por una sola compañía sino que es dirigido por una comunidad de desarrolladores y organizaciones comerciales las cuales trabajan en su desarrollo, dicha comunidad es denominada el PGDG (PostgreSQL Global Development Group).
aquí en adelante viene lo importante.
1. Crear un Usuario.
[postgres@GNU][~]$ createuser luix
Clase_Maritima=> CREATE USER pilar with password ‘pilar’;
2. Listando todos los usuarios
Clase_Maritima=> du
Clase_Maritima=> SELECT * FROM pg_user ;

3. Cambiando el Password de un Usuario.
Clase_Maritima=> ALTER USER pilar with password ’123456′;

4. Cambiando el nombre de un usuario
Clase_Maritima=> ALTER USER pilar RENAME TO manolo;

5. Borrando Usuarios
[postgres@GNU][~]$ dropuser pilar
Clase_Maritima=>drop user pilar;
6. Crear una Base Datos
[postgres@GNU][~]$ createdb Maritima
Clase_Maritima=> CREATE DATABASE marimar;

7. Listando todas las Base Datos
Clase_Maritima=> l
Clase_Maritima=> SELECT datname FROM pg_database ;
[postgres@GNU][~/data]$ psql -l

8. Cambiando el nombre de una Base datos
Clase_Maritima=> ALTER DATABASE marimar RENAME TO Maritmar;

9. Borrando una Base Datos
postgres@GNU][~]$ dropdatadb Maritima
Clase_Maritima=>drop database Maritima;

10. Accesando a una Base Datos con un usuario.
[postgres@GNU][~]$ psql -U pilar -h localhost -d Maritima
11. Creando Tablas
CREATE TABLE Pollo (
Codigo char(5),
Nombre varchar(40),
Peso integer ,
Edad date,
Famila varchar(10)
);

12. Creando tabla desde un SELECT
Clase_Maritima=> create table Mar as SELECT * FROM pollo;
13. Listando las Tablas creadas
Clase_Maritima=>dt
Clase_Maritima=> SELECT * FROM pg_tables;
14. Viendo la Estructura de una Tabla
Clase_Maritima=>d pollo

15. Cambiando el nombre de una Tabla
Clase_Maritima=> ALTER TABLE pollo RENAME TO pollos;

16. Cambiando el nombre de un campo de una Tabla
Clase_Maritima=> ALTER TABLE pollos RENAME edad TO Fecha_Muerte;

17. Agregandole un campo a una tabla
Clase_Maritima=> ALTER TABLE pollos ADD column sex char(1);

18. Borrando un campo de una tabla
Clase_Maritima=> ALTER TABLE pollos DROP sex;

19. Cambiando el tipo de dato de una columna de una tabla.
Clase_Maritima=> ALTER TABLE pollos ALTER codigo TYPE varchar;

20. Borrando una Tabla
Clase_Maritima-> DROP TABLE pollo;

21. Insertando Datos en una Tabla
Clase_Maritima=> INSERT INTO pollo VALUES ( ’1′, ‘Gallina’, 8, Current_date, ‘Criollo’);

22. Insertando datos a partir de un SELECT
Clase_Maritima=> INSERT INTO pollos (nombre, famila) SELECT bandera, codigo FROM buque ;

23. Selecionado datos de una tabla
Clase_Maritima=> SELECT * FROM pollo ;

24. Muestra el plan de ejecución de la sentencia
Clase_Maritima=# EXPLAIN SELECT * FROM buque ;

25. Para saber la cantidad de registro en una tabla (Count)
Clase_Maritima=# SELECT count(*) FROM buque ;

26. Selecionar los registros no repetidos de una campo (DISTINCT)
Clase_Maritima=# SELECT distinct(bandera) FROM buque ;

27. Actualizando datos de una tabla
Clase_Maritima=> UPDATE pollo SET nombre = ‘Gallo’ WHERE codigo=1;

28. Borrando registros de una tabla.
Clase_Maritima=> DELETE FROM pollo WHERE codigo =’1′;

29. Truncando tablas
Clase_Maritima=> TRUNCATE pollo ;

30. Agregando una llave primaria a un campo de una tabla
Clase_Maritima=> ALTER TABLE pollos ADD CONSTRAINT pk_codigo PRIMARY KEY (codigo);

31. Creando una Vista
Clase_Maritima=# CREATE VIEW v_pollo as SELECT * FROM pollos ;

32. Seleccionando datos de una Vista
Clase_Maritima=# SELECT * FROM v_pollo ;

33. Viendo las Vistas Creadas
Clase_Maritima=#dv
Clase_Maritima=# SELECT viewname FROM pg_views ;

34. Borrando una Vista
Clase_Maritima=# DROP VIEW v_pollo ;

35. Agreando una llave foraneas a un campo de una tabla
Clase_Maritima=> ALTER TABLE pollos ADD CONSTRAINT pk_codigo FOREIGN KEY (codigo) REFERENCES buque (codigo);

36. Borrando una un CONSTRAINT
Clase_Maritima=> ALTER TABLE pollos DROP CONSTRAINT pk_codigo;

37. Agregando un CONSTRAINT CHECK a un campo
Clase_Maritima=> ALTER TABLE pollos ADD CONSTRAINT c_check check (fecha_muerte > ’2007-01-01′);

38. Agregando un CONSTRAINT DEFAULT a un campo
Clase_Maritima=> ALTER TABLE pollos ALTER peso SET DEFAULT 23;

39. Creando un índice a una tabla
Clase_Maritima=> CREATE INDEX pkU_pollo ON pollos (codigo);

40. Creando un indice unico
Clase_Maritima=> CREATE UNIQUE INDEX pku_pollo ON pollos (peso );

41. Cambiandole el nombre a un indice
Clase_Maritima=> ALTER INDEX pku_pollo RENAME TO pki_pollo;

42. Ver los indices creados en una Base Datos
Clase_Maritima=>di
Clase_Maritima=> SELECT indexname, tablename FROM pg_indexes;

43. Borrando un indice
Clase_Maritima=> DROP INDEX pku_pollo ;

44. Creando un sequence
Clase_Maritima=> CREATE SEQUENCE s_mari start with 1000 increment by 2 maxvalue 1100;

45. Ver el siguente valor de un sequence
Clase_Maritima=> SELECT nextval(‘s_mari’);

46. Ver el valor actual de un sequence
Clase_Maritima=> SELECT currval(‘s_mari’);

47. Modificar el valor inicial de un sequence
Clase_Maritima=> SELECT setval(‘s_mari’, 1000);

48. Utilizando INNER JOIN
Clase_Maritima=# SELECT * FROM files f Inner Join lineas l ON l.codigo=f.linea;

49. Utilizando LEFT OUTER JOIN
Clase_Maritima=# SELECT * FROM files f LEFT OUTER JOIN lineas l ON l.codigo=f.linea;

50. Utilizando RIGHT OUTER JOIN
Clase_Maritima=# SELECT * FROM files f RIGHT OUTER JOIN lineas l ON l.codigo=f.linea;

51. Utilizando FULL OUTER JOIN
Clase_Maritima=# SELECT * FROM files f FULL OUTER JOIN lineas l ON l.codigo=f.linea;

52. Utilizando LEFT OUTER JOIN
Clase_Maritima=# SELECT * FROM files f LEFT Join lineas l USING(Linea);

53. Utilizando operador Mayor que
Clase_Maritima=# SELECT buque, loa FROM buque WHERE loa > 1000;

54. Utilizando operador Menor que
Clase_Maritima=# SELECT buque, loa FROM buque WHERE loa < 1000;

55. Utilizando operador Igual
Clase_Maritima=# SELECT buque, loa FROM buque WHERE buque=’AIDA’;

56. Utilizando operador Menor o igual que
Clase_Maritima=# SELECT buque, loa FROM buque WHERE loa <= 1000;

57. Utilizando operador Mayor o igual que
Clase_Maritima=# SELECT buque, loa FROM buque WHERE loa >= 1000;

58. Utilizando operador No igual
Clase_Maritima=# SELECT buque, loa FROM buque WHERE loa <> 1000;
Clase_Maritima=# SELECT buque, loa FROM buque WHERE loa != 1000;

59. Utilizando operador Concatenación
Clase_Maritima=# SELECT buque||’ ‘ ||dueno FROM buque ;

60. Utilizando EXISTS
SELECT * FROM boardingclerk WHERE exists(SELECT 1 FROM files);

61. Utilizando conector IN
SELECT * FROM files WHERE boarding_clerk IN (31, 33, 35);
SELECT * FROM files WHERE boarding_clerk NOT IN (31, 33, 35);

62. La cláusula ORDER BY
Clase_Maritima=# SELECT * FROM puertos ORDER BY 1 ASC;
Clase_Maritima=# SELECT codigo, puerto FROM puertos ORDER BY puerto DESC;

63. La cláusula GROUP BY
Clase_Maritima=# SELECT buque, count(*) FROM files GROUP BY buque;

64. Funciones para calcular
Clase_Maritima=# SELECT AVG(LOA) FROM BUQUE;
Clase_Maritima=# SELECT MAX(LOA) FROM BUQUE;
Clase_Maritima=# SELECT MIN(LOA) FROM BUQUE;
Clase_Maritima=# SELECT SUM(LOA) FROM BUQUE;

65. Operaciones de conjunto (UNION).
SELECT linea FROM files
union
SELECT codigo FROM lineas ;

66. Operaciones de conjunto (UNION ALL).
SELECT linea FROM files
union all
SELECT codigo FROM lineas ;

67. Operaciones de conjunto (INTERSECT).
SELECT linea FROM files
INTERSECT
SELECT codigo FROM lineas ;

68. Utilizando operadores aritméticos
FCLD=# SELECT 8+3 as Suma;
FCLD=# SELECT 8-3 as Resta;
FCLD=# SELECT 8/3 as Divide;
FCLD=# SELECT 8*3 as Multiplica;

69. Utilizando Funciones Matemáticas
FCLD=# SELECT 20-233 as Resta ; — El resultado Sera Negativo
FCLD=# SELECT abs(20-233) as Resta ; Esta Funcion
FCLD=# SELECT cbrt(27); — Retorna El cubo
FCLD=# SELECT round(99.4);
FCLD=# SELECT round(99.2, 3);
FCLD=# SELECT pi();
FCLD=# SELECT trunc(99.1);

70. Funciones Cadenas
FCLD=# SELECT ‘Jose’||’Paredes’;
FCLD=# SELECT bit_length(‘k’) ;
FCLD=# SELECT char_length(‘jose’);
FCLD=# SELECT lower(‘GNU’);
FCLD=# SELECT upper(‘gnu’);
FCLD=# SELECT initcap(‘manuel’);
FCLD=# SELECT ascii(‘K’);
FCLD=# SELECT chr(75);
FCLD=# SELECT md5(’1′);

71. Funciones Fechas y Horas
FCLD=# SELECT abstime(‘now’::timestamp); –convierte a abstime
FCLD=# SELECT age(‘now’,’1957-06-13′::timestamp); –preserva meses y años
FCLD=# SELECT to_char(current_timestamp,’HH12:MI:SS’); –convierte datetime a string
FCLD=# SELECT to_char( now(), ‘HH12:MI:SS’);
FCLD=# SELECT current_date;
FCLD=# SELECT current_timestamp;
Clase_Maritima=# SELECT to_date(fecha_llegada, ‘Mon MM YY’) FROM files ;
Clase_Maritima=# SELECT to_char(to_date(fecha_llegada, ‘Mon MM YY’), ‘YYYY-Month-Day’) FROM files ;
FCLD=# SELECT to_date(’08 Dec 2007 13′, ‘DD Mon YYYY HH’); –convierte string a date

72. Los conectores lógicos en SQL son AND-OR- NOT
Clase_Maritima=# SELECT buque, capitan, bandera, loa FROM buque WHERE capitan like ‘A%’ AND loa <1000 OR loa=2450;

73. Copiando datos desde un archivo a una tabla
COPY buque FROM ‘/var/lib/pgsql/Buquedatos.txt’;

CREAR CARPETAR - COPIAR ARCHIVOS.wmv

lunes, 20 de enero de 2014

How To Create a New User and Grant Permissions in MySQL

How To Create a New User and Grant Permissions in MySQL

How To Create a New User and Grant Permissions in MySQL

Published On: 12 Jun 15:55

What the Red Means

The lines that the user needs to enter or customize will be in red in this tutorial!

The rest should mostly be copy-and-pastable.

About MySQL

MySQL is an open source database management software that helps users store, organize, and later retrieve data. It has a variety of options to grant specific users nuanced permissions within the tables and databases—this tutorial will give a short overview of a few of the many options.

How to Create a New User

In Part 1 of the MySQL Tutorial, we did all of the editing in MySQL as the root user, with full access to all of the databases. However, in the cases where more restrictions may be required, there are ways to create users with custom permissions.

Let’s start by making a new user within the MySQL shell:
CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password';

Sadly, at this point newuser has no permissions to do anything with the databases. In fact, if newuser even tries to login (with the password, password), they will not be able to reach the MySQL shell.

Therefore, the first thing to do is to provide the user with access to the information they will need.
GRANT ALL PRIVILEGES ON * . * TO 'newuser'@'localhost';

The asterisks in this command refer to the database and table (respectively) that they can access—this specific command allows to the user to read, edit, execute and perform all tasks across all the databases and tables.

Once you have finalized the permissions that you want to set up for your new users, always be sure to reload all the privileges.
FLUSH PRIVILEGES;

Your changes will now be in effect.

How To Grant Different User Permissions

Here is a short list of other common possible permissions that users can enjoy.

  • ALL PRIVILEGES- as we saw previously, this would allow a MySQL user all access to a designated database (or if no database is selected, across the system)

  • CREATE- allows them to create new tables or databases

  • DROP- allows them to them to delete tables or databases

  • DELETE- allows them to delete rows from tables

  • INSERT- allows them to insert rows into tables

  • SELECT- allows them to use the Select command to read through databases

  • UPDATE- allow them to update table rows

  • GRANT OPTION- allows them to grant or remove other users' privileges

To provide a specific user with a permission, you can use this framework:
 GRANT [type of permission] ON [database name].[table name] TO ‘[username]’@'localhost’;

If you want to give them access to any database or to any table, make sure to put an asterisk (*) in the place of the database name or table name.

Each time you update or change a permission be sure to use the Flush Privileges command.

If you need to revoke a permission, the structure is almost identical to granting it:
 REVOKE [type of permission] ON [database name].[table name] FROM ‘[username]’@‘localhost’;

Just as you can delete databases with DROP, you can use DROP to delete a user altogether:
 DROP USER ‘demo’@‘localhost’;

To test out your new user, log out by typing
 quit 
and log back in with this command in terminal:
mysql -u [username]-p

MySQL - CREATE USER with GRANT Privileges in Terminal

Pagina para consultar todo lo que es programacion y base de datos

Pagina para consultar todo lo que es programacion y base de datos

start Over Flow

Base de datos en MySQL

Como crear una base de datos desde consola de MYSQL.mp4

sábado, 18 de enero de 2014

Ques es evt.getButton()

capturar eventos del mouse en Java 

miércoles, 15 de abril de 2009

Principales eventos de ratón

Para obtener información de una acción del ratón sobre un determinado elemento de la ventana, o sobre una ventana, se debe crear un método asociado al evento deseado.
Para crear ese tipo de métodos desde NetBeans se dispone del menú contextual o la ventana de Propiedades de la parte derecha que dispone de una pestaña Eventos.
Al crear uno de estos métodos, automáticamente se define un parámetro que recoge información sobre el evento producido. Ese parámetro recibe el nombre evt si se crea automáticamente con NetBeans. Ese es el nombre que debe utilizarse para llamar a los métodos.
Por ejempo, uno de los métodos puede ser:
private void formMouseMoved(java.awt.event.MouseEvent evt)

Eventos

  • mouseMoved: se ha movido el ratón.
  • mouseClicked: se ha hecho clic con algún botón del ratón.
  • mouseWheelMoved: se ha movido la rueda del ratón.
  • mouseDragged: se ha movido el ratón manteniendo pulsado algún botón.
  • mousePressed: se ha pulsado algún botón.
  • mouseReleased: se ha soltado algún botón.
  • mouseEntered: el puntero del ratón está sobre el elemento en el que está definido el evento.
  • mouseExited: el puntero del ratón ha dejado de estar sobre el elemento en el que está definido el evento.

Métodos

  • evt.getX() y evt.getY() permiten obtener la posición (coordenadas X e Y) en la que se encuentra el puntero del ratón respecto al objeto donde se haya definido el evento.
  • evt.getButton() retorna un valor entero con el número del botón pulsado (1: izquierdo, 2: central o rueda, 3: derecho).
  • evt.getClickCount() retorna el número de clic seguidos que se han realizado.
  • evt.getWheelRotation() retorna 1 cada vez que se mueve la rueda hacia atrás y -1 si se hace hacia delante.

Ejemplo


    private void panel1MouseClicked(java.awt.event.MouseEvent evt)
    {
        System.out.print("Se ha hecho clic en: ");
        System.out.println(evt.getX() + "," + evt.getY());
        System.out.print("Con el botón: ");
        switch(evt.getButton())
        {
            case 1:
                System.out.println("izquierdo");
                break;
            case 2:
                System.out.println("central o la rueda");
                break;
            case 3:
                System.out.println("derecho");
                break;
        }
        System.out.print("Se ha pulsado ");
        System.out.println(evt.getClickCount() + " veces seguidas");
    }                            

martes, 14 de abril de 2009

Movimiento de gráficos mediante teclas en Java

La explicación del movimiento de un gráfico en Java mediante la pulsación de teclas está basada en este caso en un ejemplo similar al utilizado en el artículo "Movimiento de gráficos mediante botones en Java", por lo que debe utilizarse esa otra explicación para conocer los atributos y métodos creados en el panel que se ha utilizado para la bola que se va a mover.

Descarga del ejemplo completo.


En la ventana principal se debe realizar el control de las teclas pulsadas. Para ello se declara el controlador de eventos de pulsaciones del teclado. Una de las formas más sencillas es a través del menú contextual de la ventana: Eventos > Key > KeyPressed. Es importante asegurarse que se hace sobre la ventana y no sobre un componente de ella ya que se asignaría el control del teclado sólo a ese componente.


Este tipo de evento (keyPressed) se repite mientras se mantenga pulsada la tecla. Si se desea un evento que sólo sea llamado con cada pulsación de la tecla se debe usar keyReleased.

Otra forma de asignar código al evento es mediate la ventana Eventos de la parte derecha:

Al asignar un controlador a uno de esos eventos se abre el editor de código donde se deben escribir las sentencias que se ejecutarán al pulsar una tecla.

    private void formKeyPressed(java.awt.event.KeyEvent evt)                              
    {                                  
       switch(evt.getKeyCode())
       {
           case KeyEvent.VK_RIGHT:
               tablero1.moverDerecha();
               break;
           case KeyEvent.VK_LEFT:
               tablero1.moverIzquierda();
               break;
           case KeyEvent.VK_UP:
               tablero1.moverArriba();
               break;
           case KeyEvent.VK_DOWN:
               tablero1.moverAbajo();
               break;
       }
    }      

El parámetro evt que aparece permite distinguir qué tecla se ha pulsado, a través de su método getKeyCode(). Este método retorna un valor entero con el código de la tecla que se ha pulsado. Si se conoce el valor del código de la tecla deseada se puede hacer una comparación directamente con el valor numérico. Es más cómodo utilizar las contantes que ya están declaradas para los códigos de teclas (KeyEvent.VK_nombreTecla). Para conocer los nombres de teclas que existen, en NetBeans se tiene la ventaja de que al escribir KeyEvent seguido del punto aparecen todas las constantes y métodos que tiene definidas.

En este ejempo se ha utilizado la sentencia switch para realizar las comparaciones, pero es posible hacer cualquier otro tipo de comparación como if o utilizarlo en bucles.

Movimiento de gráficos mediante botones en Java

Se debe partir de un panel (jPanel) integrado en una ventana (jFrame) tal como se ha explicado en el artículo Gráficos en Java.

Esta explicación se basa en un ejemplo que realiza el movimiento de una bola utilizando cuatro botones para subir, bajar y desplazar a la derecha e izquierda. Descarga del ejemplo completo para NetBeans.

Hay declarados dos atributos en la clase Tablero (jPanel) con las coordenadas donde se debe mostrar la bola, que inicialmente están inicializados para que se muestre en la parte central del tablero. A través de la actualización de los valores de esos atributos se realizará el movimiento de la bola.

public class Tablero extends javax.swing.JPanel {
    private int posX = 45;
    private int posY = 45;

La bola se dibujará en el método paint utilizando las coordenadas anteriores, con un tamaño 10.

    public void paint(Graphics g)
    {
        super.paint(g);
        g.fillOval(posX, posY, 10, 10);
    }

En el códido del panel se han definido una serie de métodos que realizan las operaciones de movimiento deseado. En cada movimiento se modifica el atributo correspondiente para cambiar la posición de la bola y se hace la llamada al método repaint para que se ejecute de nuevo el código del paint visto antes y que se encarga de mostrar la bola.

    public void moverArriba()
    {
        posY--;
        repaint();
    }

    public void moverAbajo()
    {
        posY++;
        repaint();
    }

    public void moverDerecha()
    {
        posX++;
        repaint();
    }

    public void moverIzquierda()
    {
        posX--;
        repaint();
    }

Los botones que permiten al usuario realizar el movimiento se han incluido en la ventana, fuera del panel.


A cada botón se le ha asignado el código necesario para que realice la llamada al método que corresponda del panel para hacer el movimiento de la bola.

    private void botonArribaActionPerformed(java.awt.event.ActionEvent evt)
    {                                              
        tablero1.moverArriba();
    }                                          

    private void botonAbajoActionPerformed(java.awt.event.ActionEvent evt)
    {                                              
        tablero1.moverAbajo();
    }                                        

    private void botonIzquierdaActionPerformed(java.awt.event.ActionEvent evt)
    {                                                  
        tablero1.moverIzquierda();
    }                                            

    private void botonDerechaActionPerformed(java.awt.event.ActionEvent evt)
    {                                                
        tablero1.moverDerecha();
    }

Hay que observar el nombre que ha recibido el panel al integrarlo en la ventana. En este caso le ha dado el nombre tablero1. Este nombre puede verse en las propiedades al seleccionar el panel.


lunes, 13 de abril de 2009

Mostrar imágenes en Java

Dentro del método paint de un panel se puede insertar el código para que se cargue una imagen almacenada en un archivo, para que sea mostrada dentro de dicho panel.

Para incluir una imagen se debe llamar al método drawImage de la clase Graphics. A este método se le pasan cuatro parámetros: El primero de ellos es la referencia al objeto Image o BufferedImage que contiene la imagen a mostrar. El segundo y tercer parámetro indican la posición en la que se mostrará.

Para crear el objeto de la clase Image o BufferedImage se puede utilizar el método read de la clase ImageIO, al que se le para la referencia a un objeto File con la ruta al archivo que contiene la imagen.

    public void paint(Graphics g)
    {
        super.paint(g);

        BufferedImage img = null;
        int posx=0, posy=0;
        try
        {
            img = ImageIO.read(new File("src/recursos/ejemplo.png"));
        }
        catch (IOException e)
        {
            //Control de excepción si no se encuentra el archivo
        }
        g.drawImage(img, posx, posy, null);
    }
En este ejemplo se mostraría la imagen "ejemplo.png" que se encuentra en la carpeta "src/recursos" del proyecto. Se indica la posición 0,0 por lo que aparecerá en la esquina superior izquierda del panel.