Beginning Linux Programming Third Edition phần 5 potx

89 1.1K 0
Beginning Linux Programming Third Edition phần 5 potx

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

INSERT INTO children VALUES (1,’Jenny’,17); INSERT INTO children VALUES (2,’Andrew’,13); INSERT INTO children VALUES (3,’Gavin’,4); INSERT INTO children VALUES (4,’Duncan’,2); INSERT INTO children VALUES (5,’Emma’,0); INSERT INTO children VALUES (6,’Alex’,11); INSERT INTO children VALUES (7,’Adrian’,5); mysqlimport The mysqlimport command is the equally useful cousin of mysqldump. Using mysqlimport, you can read in large quantities of data from an input file. The only command-specific parameters required are a filename and a database. Generally, you’ll be reading in a file created by mysqldump; but it’s possible to manually create a file that can be read by mysqlimport as well. It’s also possible to perform SQL commands from a text file by simply running mysql with input redi- rected from a file, as we mentioned earlier. mysqlshow This little utility can provide quick information about your MySQL installation and its component databases. ❑ With no parameters, it lists all available databases. ❑ With a database as a parameter, it lists the tables in that database. ❑ With both a database and a table name, it lists the columns in that table. ❑ With a database, table, and column, it lists the details of the specified column. Creating Users and Giving Them Permissions As a MySQL administrator, one of your most common tasks will be user maintenance. Before you try using a wrench on your users (a tempting possibility on the best of days), we mean adding and remov- ing users from MySQL and managing their privileges. Starting with MySQL 3.22, users are managed with the grant and revoke commands from within the MySQL monitor—a task considerably less daunting than editing the privilege tables directly as was necessary in previous versions. grant The MySQL grant command closely, though not exactly, follows SQL92. The general format is grant <privilege> on <object> to <user> [identified by user-password] [with grant]; There are several privilege values that can be granted, shown in the following table: alter Alter tables and indexes. create Create databases and tables. delete Delete data from the database. 314 Chapter 8 b544977 Ch08.qxd 12/1/03 8:56 AM Page 314 drop Remove databases and tables. index Manage indexes. insert Add data to the database. select Retrieve data. update Modify data. all All the above. There are also several special administration privileges, but these do not concern us here. The object on which you grant these privileges is identified as databasename.tablename and in the best Unix tradition, * is the anything-goes operator so that database.* means every object in the database. If the specified user already exists, privileges are edited to reflect your changes. If no such user exists, the user is created with the specified privileges. You should specify user and host in the same command to get the full flexibility of the MySQL permission scheme. In SQL syntax, the special character % stands for the wildcard character, much the same as * in a shell environment. You can, of course, issue separate commands for each desired privilege set; but if, for exam- ple, you want to grant access to user rick from any host in the domain, you could describe rick as rick@’%.docbox.co.uk’ Any use of the wildcard character must be enclosed in quotes to set it off from any literal text. You can also use IP/Netmask notation (N.N.N.N/M.M.M.M) to set a network address for access control. Just as we earlier used rick@’192.168.0.0/255.255.255.0’ to grant access to rick from any local network computer, we can specify rick@’192.168.0.1’ to limit rick’s access to a single workstation or specify rick@’192.0.0.0/255.0.0.0’ to broaden the scope to include any machine in the 192 class A network. As one more example, mysql> grant all on foo.* to rick@’%’ identified by ‘bar’; will create a user rick, with full permissions on the database foo, to connect from any machine with an initial password of bar. If the database foo does not yet exist, then the user rick will now have permissions to create it using the create database SQL command. The identified by clause is optional; but it’s a good idea to set the password each time to ensure there is never a hole in your security. 315 MySQL b544977 Ch08.qxd 12/1/03 8:56 AM Page 315 Typically, the with grant option is used only to create a secondary administrative user; however, it can be used to allow a newly created user to confer the privileges granted to her on other users. Always use with grant judiciously. revoke Naturally, the administrator that giveth also taketh away, and the administrator can do so with the revoke command: revoke a privilege on an object from a user; using much the same format as the grant command. For example, revoke insert on foo.* from rick@’%’; The revoke command, however, does not delete users. If you wish to completely remove a user, don’t simply modify their privileges, but use revoke to remove their privileges. Then you can completely remove them from the user table with mysql> use mysql mysql> DELETE FROM user WHERE user = “rick” mysql> FLUSH PRIVILEGES; In declining to specify a host, we ensure that we get rid of every instance of the MySQL user that we want removed. Understand that delete is not part of the same concept as grant and revoke. It’s SQL syntax that happens to be necessary as a result of the way MySQL handles permissions. Notice that the use command is not necessary with grant and revoke, as MySQL knows in these instances you want manipulate the permissions tables. mysql> use mysql mysql> DELETE FROM user WHERE user = “rick” mysql> FLUSH PRIVILEGES; Passwords If you want to specify passwords for existing users who do not already have them, or you wish to change your own or somebody else’s password, you’ll need to connect to the MySQL server as the root user, select the mysql database, and then mysql> select host, user, password from user; You should get a list like this: + + + + | host | user | password | + + + + | localhost | root | 67457e226a1a15bd | | localhost | foo | | + + + + 2 rows in set (0.00 sec) 316 Chapter 8 b544977 Ch08.qxd 12/1/03 8:56 AM Page 316 Say you want to assign the password bar to user foo; you can do so like this: mysql> UPDATE user SET password = password(‘bar’) WHERE user = ‘foo’; Display the relevant columns in the user table again: mysql> SELECT host, user, password FROM user; + + + + | host | user | password | + + + + | localhost | root | 65457e236g1a1wbq | | localhost | foo | 7c9e0a41222752fa | + + + + 2 rows in set (0.00 sec) mysql> Sure enough, the user foo now has a password. In MySQL 4.1 the password scheme has been updated. However, you can still set a password using the old algorithm for backward compatibility with the function OLD_PASSWORD(‘password to set’). This implementation is still a little ragged, but it should become more reliable as updated versions are released. Creating a Database Let’s start with a database called rick. You may recall that we’ve already created a user with the same name. mysql> GRANT ALL ON *.* TO rick@localhost IDENTIFIED BY ‘secretpassword’; Let’s test that privilege set by logging in as rick and creating the database: mysql> quit Bye $ mysql –u rick -p Enter password: mysql> CREATE DATABASE rick; Now we’ll tell MySQL we want to use our new database: mysql> use rick Now we can populate this database with the tables and information we want. On future logins, we can specify the database on the command line, bypassing the need for the use command: $ mysql –u rick -p rick We will then automatically change to use the database rick. 317 MySQL b544977 Ch08.qxd 12/1/03 8:56 AM Page 317 Data Types So now we have a running MySQL server, a secure login for our user, and a database ready to use. What’s next? Well, now we need to create some tables with columns to store our data. Before we can do that, however, we need to know about the data types that MySQL supports. MySQL data types are fairly standard, so we will just run briefly though the main types here. As always, the MySQL manual on the MySQL Web site discusses this in more detail. Boolean A Boolean column can be defined using the keyword BOOL. As you would expect, it can hold TRUE and FALSE values. It may also hold the special database “unknown” value NULL. Character A variety of character types are available and are shown in the following table. The first three are stan- dard and the remaining three specific to MySQL. We suggest you stick to the standard types if practical. Definition Meaning CHAR A single character. CHAR(N) A character string on exactly N characters, which will be padded with space characters if necessary. Limited to 255 characters. VARCHAR(N) A variable-length array of N characters. Limited to 255 characters. TINYTEXT Similar to VARCHAR(N). MEDIUMTEXT A text string of up to 65,535 characters. LONGTEXT A text string of up to 2 32 –1 characters. Number The number types are broken down into integer and floating point number types, as shown in the fol- lowing table: Definition Type Meaning TINYINT Integer An 8-bit data type. SMALLINT Integer A 16-bit data type. MEDIUMINT Integer A 24-bit data type. INT Integer A 32-bit data type. This is a standard type, and a good general purpose choice. BIGINT Integer A 64-bit signed data type. FLOAT(P) Floating A floating point number with at least P digits of precision. 318 Chapter 8 b544977 Ch08.qxd 12/1/03 8:56 AM Page 318 Definition Type Meaning DOUBLE(D, N) Floating A signed double-precision floating point number, with D digits and N decimal places. NUMERIC(P, S) Floating A real number with a total of P digits, with S of the digits after the decimal place. Unlike DOUBLE, this is an exact number, so it is better for storing currency, but less efficiently processed. DECIMAL(P, S) Floating A synonym for NUMERIC. In general, we suggest you stick to INT, DOUBLE, and NUMERIC types, as these are closest to the standard SQL types. The other types are nonstandard and may not be available in other database systems if you find you need to move your data at some point in the future. Temporal Four temporal data types are available, shown in the following table: Definition Meaning DATE Stores dates between January 1, 1000, and December 31, 9999. TIME Stores times between –838:59:59 and 838:59:59. TIMESTAMP Stores a timestamp between January 1, 1970, and the year 2037. DATETIME Stores dates between January 1, 1000, and the last second of December 31, 9999. Creating a Table Now that we have our database server running, know how to assign user permissions, and know how to create a database and some basic database types, we can move on to creating tables. A database table is simply a sequence of rows, each of which consists of a fixed set of columns. It’s rather like a spreadsheet, except that each row must have exactly the same number and type of columns, and each row must, in some way, be different from all other rows in the table. A database can, within reason, contain pretty much an unlimited number of tables. However, very few databases need more than 100 tables, and for most small systems 10 or 20 tables usually suffice. The full SQL syntax for creating database objects, known as DDL (data definition language), is too complex to go into fully in one chapter; the full details can be found in the documentation section of the MySQL Web site. The basic syntax for creating a table is CREATE TABLE <table_name> ( column type [NULL | NOT NULL] [AUTO_INCREMENT] [PRIMARY KEY] 319 MySQL b544977 Ch08.qxd 12/1/03 8:56 AM Page 319 [, ] [, PRIMARY KEY ( column [, ] ) ] ) You can discard tables using the DROP TABLE syntax, which is very simple: DROP TABLE <table_name> For now, there are just a small number of additional keywords we need to know to get up to speed with creating tables, shown in the following table: Keyword Meaning AUTO_INCREMENT This special keyword tells MySQL that, whenever you write a NULL into this column, it should automatically fill in the column data using an automatically allocated incrementing number. This is an immensely useful feature; it allows us to use MySQL to automatically assign unique numbers to rows in our tables. In other databases this functionality is often provided by a serial type, or is managed more explicitly with a sequence. NULL A special database value that is normally used to mean “not known,” but can also be used to mean “not relevant.” For example, if you are filling in a table with employee details, you might have a column for e-mail address, but perhaps some employees don’t have a company e-mail address. In this case, you would store a NULL against the e-mail address for that employee to show that the information was not rele- vant to that particular person. The syntax NOT NULL means that this column cannot store a NULL value, and it can be useful to prevent columns from holding NULL values if, for example, the value must always be known, such as an employee’s last name. PRIMARY KEY Indicates that the data for this column will be unique and different in every row in this table. Each table can have just a single primary key. It’s much easier to see table creation in practice than to look at the base syntax, so let’s do that now by creating a table called children that will store a unique number for each child, a first name, and an age. We’ll make the child number a primary key: CREATE table children ( childno INTEGER AUTO_INCREMENT NOT NULL PRIMARY KEY, fname VARCHAR(30), age INTEGER ); Notice that, unlike most programming languages, the column name (childno) comes before the column type ( INTEGER). 320 Chapter 8 b544977 Ch08.qxd 12/1/03 8:56 AM Page 320 We can also use a syntax that defines the primary key separately from the column; here’s a session that shows the alternative syntax: mysql> use rick Database changed mysql> CREATE table children ( -> childno INTEGER AUTO_INCREMENT NOT NULL, -> fname varchar(30), -> age INTEGER, -> PRIMARY KEY(childno) -> ); Query OK, 0 rows affected (0.04 sec) mysql> Notice how we can write the SQL across several lines, and MySQL uses the -> prompt to show we are on a continuation line. Also notice, as mentioned earlier, we terminate the SQL with a semicolon to indi- cate we have finished and are ready for the database to process the request. If you make a mistake, MySQL should allow you to scroll backward through previous commands, edit them, and re-enter them by simply pressing Enter. Now we have a table to which we can add some data. We do this with the INSERT SQL command. Since we defined the childno column as an AUTO_INCREMENT column, we don’t give any data from that col- umn; we simply allow MySQL to allocate a unique number. We can check whether the data was stored successfully by SELECTing the data from the table: mysql> INSERT INTO children(fname, age) VALUES(“Jenny”, 17); Query OK, 1 row affected (0.07 sec) mysql> INSERT INTO children(fname, age) VALUES(“Andrew”, 13); Query OK, 1 row affected (0.01 sec) mysql> SELECT childno, fname, age FROM children; + + + + | childno | fname | age | + + + + | 1 | Jenny | 17 | | 2 | Andrew | 13 | + + + + 2 rows in set (0.06 sec) mysql> Rather than explicitly list the columns we wanted to select, we could just have used an asterisk (*) for the columns, which will list all columns in the named table. In production code you should always explicitly name the column you wish to select for interactive use, but an asterisk is sometimes conve- nient during development because it saves typing and the need to remember exact column names. We don’t have space in this chapter to go into full details of SQL, much less database design. For more information see www.mysql.com. 321 MySQL b544977 Ch08.qxd 12/1/03 8:56 AM Page 321 Graphical Tools Manipulating tables and data on the command line is all well and good, but these days many people prefer graphical tools. MySQL has had a graphical tool known as MySQLGUI for some time. This tool is still available from the MySQL Web site, but development is now concentrated on an alternative tool, the MySQL Control Center, or MySQLCC. The MySQL Control Center is a very useful all-around tool, and one well worth installing. We strongly suggest you look at MySQLCC; it’s a powerful, stable, and easy-to-use graphical interface for MySQL that is available precompiled for both Linux and Windows (even the source code is available if you want it). It allows you to both administer a MySQL server and execute SQL through a GUI interface. If a MySQLCC is not available on your Linux distribution, you can download a copy from the MySQL Web site and follow the simple installation instructions. Alternatively, you can manage your copy of MySQL running on your Linux server directly from MySQLCC running on a Windows desktop. They look and run almost identically. The first time you run MySQLCC, you will be presented with a blank Control Center window, with an empty Console Manager, as shown in Figure 8-2. Hovering the mouse over the first icon on the toolbar reveals that this is the icon for creating a new connection. Figure 8-2 322 Chapter 8 b544977 Ch08.qxd 12/1/03 8:56 AM Page 322 When you click this button, you will be asked for some basic details in an additional popup window (see Figure 8-3). Figure 8-3 If you want to manage your server remotely from a Windows PC, then configuration is almost identical, except that you need to enter a host name or IP address in the Host Name field, as shown in Figure 8-4. Figure 8-4 323 MySQL b544977 Ch08.qxd 12/1/03 8:56 AM Page 323 [...]... VALUES VALUES (1,’Jenny’,17); (2,’Andrew’,13); (3,’Gavin’,4); (4,’Duncan’,2); (5, ’Emma’,0); (6,’Alex’,11); (7,’Adrian’ ,5) ; MySQL We can now sign back on to MySQL, selecting the database foo, and execute this file: $ mysql -u rick -psecret foo Welcome to the MySQL monitor Commands end with ; or \g Your MySQL connection id is 15 to server version: 4.0.12 Type ‘help;’ or ‘\h’ for help Type ‘\c’ to clear... or the basic mysql client MySQL can be accessed from many different languages We know of ❑ C ❑ C++ ❑ Java 3 25 Chapter 8 ❑ Perl ❑ Python ❑ REXX ❑ Tcl ❑ PHP An ODBC drive is also available for accessing MySQL from Windows-native applications such as Access; and there is even an ODBC driver for Linux, although little reason exists to use it In this chapter, we’ll limit ourselves to the C interface because... the name of the machine the server is running on) should be displayed in the list of MySQL servers, and by clicking it you should be able to drop down more information, as you can see in Figure 8 -5 Figure 8 -5 If you explore the database section, you can see the tables, and by right-clicking a table, you can edit the table definition or the data in the table, as you can see in Figure 8-6 324 MySQL Figure... children table has data in it, like this: + -+ + + | childno | fname | age | + -+ + + | 1 | Jenny | 17 | | 2 | Andrew | 13 | | 3 | Gavin | 4 | | 4 | Duncan | 2 | | 5 | Emma | 1 | | 6 | Alex | 11 | | 7 | Adrian | 5 | | 8 | Ann | 3 | | 9 | Ann | 4 | | 10 | Ann | 3 | | 11 | Ann | 4 | + -+ + + Notice that there are four children matching the name Ann If we execute update1, we might... gcc -I/usr/include/mysql connect1.c -L/usr/lib/mysql -lmysqlclient -lz -o connect1 329 Chapter 8 You may find a simpler line, such as the one that follows, works on newer distributions such as Red Hat Linux 9 and later $ gcc -I/usr/include/mysql connect1.c -lmysqlclient -o connect1 When we run it, we simply get a message saying the connection succeeded: $ /connect1 Connection success $ In Chapter 9,... structures We can force an error by choosing an incorrect user or password, and we will still get an error code similar to that offered by the mysql tool $ /connect2 Connection failed Connection error 10 45: Access denied for user: ‘rick@localhost’ (Using password: YES) $ Executing SQL Statements Now that we can connect to our database and correctly handle errors, let’s put our program to some real work... machine, we can optimize the connection type by specifying simply localhost here sql_user_name and sql_password are exactly what they sound like If the login name is NULL, then the login ID of the current Linux user is assumed If the password is NULL, you will be able to access data only on the server that’s accessible without a password The password is encrypted before being sent across the network 326... set (0.01 sec) mysql> INSERT INTO children(fname, age) VALUES(‘Harry’, 17); Query OK, 1 row affected (0.02 sec) 334 MySQL mysql> SELECT LAST_INSERT_ID(); + + | last_insert_id() | + + | 5 | + + 1 row in set (0.00 sec) mysql> How It Works Each time we inserted a row, MySQL allocated a new id column value and kept track of it so we could retrieve it using LAST_INSERT_ID() If you... (!res) { printf(“Inserted %lu rows\n”, (unsigned long)mysql_affected_rows(&my_connection)); } else { fprintf(stderr, “Insert error %d: %s\n”, mysql_errno(&my_connection), mysql_error(&my_connection)); } 3 35 Chapter 8 res = mysql_query(&my_connection, “SELECT LAST_INSERT_ID()”); if (res) { printf(“SELECT error: %s\n”, mysql_error(&my_connection)); } else { res_ptr = mysql_use_result(&my_connection); if (res_ptr)... function to allow the MySQL library to tidy up the objects it has allocated Retrieving the Data Now we can write our first data-retrieval application We want to select all records where age is greater than 5 We don’t how to process this data yet, so we’ll start by simply retrieving it The important section, where we retrieve a result set and loop through the retrieved data, is highlighted This is select1.c: . rick@’192.168.0.0/ 255 . 255 . 255 .0’ to grant access to rick from any local network computer, we can specify rick@’192.168.0.1’ to limit rick’s access to a single workstation or specify rick@’192.0.0.0/ 255 .0.0.0’. necessary. Limited to 255 characters. VARCHAR(N) A variable-length array of N characters. Limited to 255 characters. TINYTEXT Similar to VARCHAR(N). MEDIUMTEXT A text string of up to 65, 5 35 characters. LONGTEXT. password | + + + + | localhost | root | 67 457 e226a1a15bd | | localhost | foo | | + + + + 2 rows in set (0.00 sec) 316 Chapter 8 b544977 Ch08.qxd 12/1/03 8 :56 AM Page 316 Say you want to assign the

Ngày đăng: 09/08/2014, 14:21

Từ khóa liên quan

Mục lục

  • Chapter 8: MySQL

    • MySQL Administration

      • Commands

        • mysqlimport

        • mysqlshow

        • Creating Users and Giving Them Permissions

          • grant

          • revoke

          • Passwords

          • Creating a Database

            • Data Types

            • Boolean

            • Character

            • Number

            • Temporal

            • Creating a Table

            • Graphical Tools

            • Accessing MySQL Data from C

              • Connection Routines

              • Error Handling

              • Executing SQL Statements

                • SQL Statements That Return No Data

                • Discovering What You Inserted

                  • Try It Out

                  • Try It Out

                  • Statements That Return Data

                  • Processing Returned Data

                  • Miscellaneous Functions

Tài liệu cùng người dùng

Tài liệu liên quan