Java and MySQL Database Programming

Source: Internet
Author: User

Java database connection process:

 

Step 1: Install the driver and set the path

Step 1: To mysqlofficial website download mysql-connector-java-5.0.8.zip driver, decompress the copy inside the mysql-connector-java-5.0.8.jar to JDK installation directory lib folder;

 

Step 2: Set the environment variable classpath =.; % java_home %/lib/mysql-connector-java-5.0.8.jar;

 

Step 2: Programming

Step 1: load and register the JDBC driver in the program, where the JDBC-ODBC comes with JDK, the default has been registered, so do not need to register;

Class. forname ("com. MySQL. JDBC. Driver ");

Java. SQL. drivermanager. registerdriver (new COM. MySQL. JDBC. Driver (); // not required for MySQL

 

Step 2: establish a connection with the database

Connection con = java. SQL. drivermanager. getconnection (dburl, user, PWD );

Dburl indicates the jdbc url to connect to the database: JDBC: mysql: // localhost: 3306/db_name

User: Database User Name

PWD: Database Password

 

Step 3: Create a statement object and prepare to execute an SQL statement.

Statement stmt = con. createstatement ();

 

Step 4: Execute SQL statements

String SQL = "select * From tb_name ";

Resultset rs = stmt.exe cutequery (SQL );

 

Step 5: traverse records in the resultset object

While (Rs. Next ()){

String name = Rs. getstring (INDEX );

Long id = Rs. getlong (INDEX );

Int age = Rs. getint (INDEX );

}

 

Step 6: Close the database

Rs. Close ();

Stmt. Close ();

Con. Close ();

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.