Java JDBC Operation MySQL Database

Source: Internet
Author: User

First, create a database in MySQL, such as geek99db:

Create Database geek99db;

Use geek99db;

Then create a table Customertab:

CREATE TABLE Customertab (ID int primary key auto_increment,name Varcahr (), email varchar (20));

Show Table:

Show tables;

To add an element:

Insert into CUSTOMERTBL (name,email) VALUES (' Tam ', ' [email protected] ');

Display elements:

Select *from customertbl;

Second, complete the acquisition of the database under Ecplise:

First, create a Java project, create a new folder lab, copy the Mysql-connector-java-5.1.22-bin.jar (JDBC driver into this folder, and add it to the build path);

Then create a new class file with the following code:

Package jdbctest;

Import java.sql.Connection;
Import Java.sql.DriverManager;
Import Java.sql.ResultSet;
Import java.sql.SQLException;
Import java.sql.Statement;

public class Test01 {

public static void Main (string[] args) {
TODO auto-generated Method Stub

Loading the JDBC Driver
Connection Conn=null;
try {
class.forname ("Com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}

Connect to a specific database object
try {
conn=drivermanager.getconnection ("jdbc:mysql://localhost:3306/geek99db", "root", "Yuan");
} catch (SQLException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}

Create SQL Statement object, execute Query
String sql= "Select Id,name,email from Customertbl";
try {
Statement stmt =conn.createstatement ();
ResultSet rs=stmt.executequery (SQL);

Working with result sets
while (Rs.next ()) {
int Id=rs.getint (1);
String name=rs.getstring (2);
String email=rs.getstring (3);
System.out.println (id+ "," +name+ "," +email ");
}

} catch (SQLException e) {
TODO auto-generated Catch block
E.printstacktrace ();

Turn off data connections
if (conn!=null) {
try {
conn.close ();
} catch (SQLException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
}

}

}


}finally {

Java JDBC Operation MySQL Database

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.