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