JDBC connection to MySQL database and Examples

Source: Internet
Author: User
Tags driver manager

JDBC is a technology developed by Sun that can connect to databases using Java.

I. Basic JDBC knowledge

JDBC (Java Data Base connectivity, Java database connection) is a Java API used to execute SQL statements. It can provide unified access to multiple relational databases, it consists of a group of classes and interfaces written in Java. JDBC provides a standard API for database developers to build more advanced tools and interfaces so that database developers can use pure Java APIs to write database applications, it can run across platforms and is not restricted by database vendors.

1. cross-platform running:This inherits the "one-time compilation, running everywhere" feature of the Java language;

2. not restricted by database vendors:Cleverly, JDBC has two interfaces. One is for the application layer, which enables developers to call the database and process results through SQL without considering the database provider; the other is the driver layer, which processes the interaction with a specific driver. The JDBC driver can use the jdbc api to create a bridge between the Java program and the data source. The application can be moved to various drivers only once. Sun provides a driver Manager. The drivers provided by the database vendors, such as MySQL and Oracle, can be identified and work properly if they meet the requirements of the driver manager. Therefore, JDBC is not restricted by database vendors.

JDBC APIs can be used as links to connect Java applications to various relational databases, which brings convenience and negative effects. The following are the advantages and disadvantages of JDBC.Advantages:

  • Easy to operate:JDBC eliminates the need for developers to use complex drives to call commands and functions;
  • High Portability:JDBC supports different relational databases, so the same application can support access from multiple databases, as long as the corresponding driver is loaded;
  • Good versatility:The JDBC-ODBC bridge driver replaces the JDBC function with ODBC;
  • Object-oriented:Common JDBC database connections can be encapsulated into a class and called directly when used.

Disadvantages:

  • The speed of accessing data records is affected to a certain extent;
  • It is difficult to change the data source: JDBC supports multiple databases, and operations between different databases must be different, which makes it very difficult to change the data source.

2. process and principle of connecting to the database through JDBC

1,Load the driver of the specified database in the development environment. For example, in the following experiment, the database used is MySQL, so you need to download the JDBC-supported MySQL Driver (the latest is: mysql-connector-java-5.1.18-bin.jar); and the development environment is myeclipse, load the downloaded driver into the development environment (the detailed example shows how to load the driver ).

2,Load the driver in a Java program. In Java programs, you can use "class. forname ("specify the database driver") to load the driver added to the development environment. For example, the Code for loading the MySQL DATA driver is: class. forname ("com. mySQL. JDBC. driver ")

3,Create a data connection object: Create a database connection object connection through the drivermanager class. The drivermanager class acts between the Java program and the JDBC driver to check whether the loaded driver can establish a connection. Then, based on the URL, user name, and password of the database, it uses the getconnection method, create a JDBC
Connection object. For example, connection = drivermanager. geiconnection ("url for database connection", "username", "password "). Url = protocol name + IP address (Domain Name) + port + database name; user name and password are the user name and password used to log on to the database. The connection code for creating a MySQL database is as follows:

Connection connectmysql = drivermanager. geiconnection ("JDBC: mysql: // localhost: 3306/myuser", "root", "root ");


4,Create a statement object: The object used to execute a static SQL statement and return the result it generates. You can use the createstatement () method of the connection object to create a statement object. For example, statement statament = connection. createstatement (); the Code for creating a statement object is as follows:

Statement statamentmysql = connectmysql. createstatement ();


5,Call the relevant methods of the statement object to execute the corresponding SQL statement: Use the execuupdate () method to update data, including insert and delete operations, such as inserting a piece of data code into the staff table:

Statement. excuteupdate ("insert into staff (name, age, sex, address, depart, worklen, wage)" + "values ('tom1', 321, 'M', 'China ', 'personnel ', '3', '123 ')");

You can call the executequery () method of the statement object to query data. The result of the query gets the resulset object. resulset indicates the set of data returned after the database is queried, the resulset object has a pointer that can point to the current data row. Use the next () method of the object to direct the pointer to the next row, and then retrieve the data by column number or field name. If the next () method returns NULL, it indicates that no data exists in the next row. The sample code is as follows:

Resultset resultsel = statement.exe cutequery ("select * from staff ");


6,Close database connection: When the database is used up or you do not need to access the database, close the data connection in time using the close () method of connection.

Iii. JDBC application example Experiment

Lab content:Use phpMyAdmin to create a database (myuser) in MySQL and add the data required for the experiment (create a staff table and add some records); write a Java program, use JDBC to connect to a database (myuser) created in MySQL to insert, update, delete, and query the staff table.

Lab environment and development tools:Win7 operating system; jdk1.6.0 _ 26; xampp1.7.7 (MySQL 5.1, phpMyAdmin); myeclipse 8.5

Lab environment setup:Refer to my blog

  • Java environment: http://blog.csdn.net/cxwen78/article/details/6400798;
  • Windows XAMPP installation configuration use: http://blog.csdn.net/cxwen78/article/details/6847927

Experiment process and steps:

1,Download the JDBC-supported MySQL DRIVER: skip this step if you already have one. Go to the MySQL official website (http://www.mysql.com/products/connector/) to download the driver, MySQL provides different connectors for different platforms, we need DBC
Driver For MySQL (connector/J), as shown in, click Download to follow the website guide for download. Open the downloaded package (mysql-connector-java-5.1.18.zip), copy the Java package (mysql-connector-java-5.1.18-bin.jar) to the MySQL directory (only for convenience) for loading the driver.

2,Create a database: Use phpMyAdmin to log on to MySQL, create a database myuser, and insert a table named staff into it. And add some data, operation steps, after logging on to the MySQL database:

1) Create a database named myuser, encoded as utf8_general_ci (Chinese supported );

2) create a new table named staff. The table has 8 fields;

3) set 8 fields, including name, type, value length, initial value, encoding, and so on (click to view the big picture );


4) after the table is added, view the status of the staff table:


5) insert some data required for the experiment into the table. You need to insert two data entries, one for employee Lucy and the other for Lili:

3,Create a project in myeclips and add the MySQL driver to the project: The created project type can be Java project or Java Web project. The web project is created here. The project name can be obtained at will. I name it javawebchp07 ". After the creation is successful, add the MySQL driver package (mysql-connector-java-5.1.18-bin.jar) downloaded in step 1 to the build path of the project, adding process:

4,Compile the code for connecting JDBC to the MySQL database, jdbc_test.java:

Code:

Package chp07; import Java. SQL. connection; import Java. SQL. drivermanager; import Java. SQL. resultset; import Java. SQL. sqlexception; import Java. SQL. statement; public class jdbc_test {// create static global variable static connection conn; static statement st; public static void main (string [] ARGs) {insert (); // insert add Record Update (); // update record data Delete (); // Delete record query (); // query record and display}/* insert data record, and output the number of inserted data records */public static void insert () {conn = getconnection (); // first obtain the connection, connect to the database try {string SQL = "insert into staff (name, age, sex, address, depart, worklen, wage)" + "values ('tom1 ', 32, 'M', 'China', 'personnel ', '3', '000000') "; // SQL statement ST = (statement) Conn for data insertion. createstatement (); // create the statement object int COUNT = st.exe cuteupdate (SQL) for executing static SQL statements; // SQL statement for executing the insert operation, and return the number of inserted data. out. println ("insert to the staff table" + Count + "items"); // output the insert operation result Conn. close (); // close the database connection} catch (sqlexception e) {system. out. println ("failed to insert data" + E. getmessage () ;}}/* update the records that meet the requirements, and return the number of updated records */public static void Update () {conn = getconnection (); // obtain the connection first, that is, connect to the database try {string SQL = "update staff set wage = '000000' where name = 'Lucy '"; // SQL statement ST = (statement) Conn for updating data. createstatement (); // create a statement object used to execute static SQL statements. The st local variable int COUNT = st.exe cuteupdate (SQL); // The SQL statement used to execute the update operation, returns the number of updated data. out. println ("updates in the staff table" + Count + "items"); // outputs the conn processing result of the update operation. close (); // close the database connection} catch (sqlexception e) {system. out. println ("failed to update data") ;}/ * queries the database and outputs records meeting the requirements */public static void query () {conn = getconnection (); // obtain the connection first, that is, connect to the database try {string SQL = "select * from staff"; // SQL statement ST = (statement) Conn for data query. createstatement (); // create a statement object used to execute static SQL statements. The st is the local variable resultset rs = st.exe cutequery (SQL); // execute the SQL query statement, returns the result set system of the queried data. out. println ("the final query result is:"); While (RS. next () {// determine whether another data exists. // obtain the corresponding value string name = Rs Based on the field name. getstring ("name"); int age = Rs. getint ("Age"); string sex = Rs. getstring ("sex"); string address = Rs. getstring ("Address"); string depart = Rs. getstring ("depart"); string worklen = Rs. getstring ("worklen"); string wage = Rs. getstring ("wage"); // output the value of each field of the record found: system. out. println (name + "" + age + "" + sex + "" + address + "" + depart + "" + worklen + "" + wage);} Conn. close (); // close the database connection} catch (sqlexception e) {system. out. println ("failed to query data") ;}/ * delete records that meet the requirements, output information */public static void Delete () {conn = getconnection (); // get the connection first, that is, connect to the database try {string SQL = "delete from staff where name = 'lili'"; // SQL statement ST = (statement) for data deletion) conn. createstatement (); // create a statement object for executing static SQL statements. The st local variable int COUNT = st.exe cuteupdate (SQL); // execute the SQL deletion statement, returns the number of data deleted. out. println ("delete from the staff table" + Count + "data entries \ n"); // output the conn of the delete operation. close (); // close the database connection} catch (sqlexception e) {system. out. println ("failed to delete data") ;}/ * function for retrieving database connections */public static connection getconnection () {connection con = NULL; // create the connection object try {class for database connection. forname ("com. mySQL. JDBC. driver "); // load Mysql Data driver con = drivermanager. getconnection ("JDBC: mysql: // localhost: 3306/myuser", "root", "root"); // create a data connection} catch (exception e) {system. out. println ("database connection failed" + E. getmessage () ;}return con; // return the database connection established }}

Deploy the project to the server and run the result:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.