The procedure can be divided into the following steps:
1. Create a database
Create users, username, and password in the database work.
2. Create a New java project in MyEclipse and name it jdbcexample
3. Add the connection class package (mysql-connector-java-5.1.6-bin.jar) required to connect to MySQL-> this package is the top priority, should not be omitted.
4. Create an implementation class in the project:
JDBCExample01.java
Code
Package com. example;
Import java. SQL .*;
Import com. mysql. jdbc. PreparedStatement;
Public class JDBCExample {
Public static void main (String [] args ){
String driver = "com. mysql. jdbc. Driver ";
String url = "jdbc: mysql: // localhost: 3306/work ";
String username = "root ";
String password = "";
String SQL = "insert into users (username, password) values (?,?) ";
Try {
Class. forName (driver );
Connection conn = DriverManager. getConnection (url, username,
Password );
// Statement stat = conn. createStatement ();
PreparedStatement pstmt = (PreparedStatement) conn
. PrepareStatement (SQL );
Pstmt. setString (1, "xiaoxiao ");
Pstmt. setString (2, "thinking in java ");
Pstmt.exe cuteUpdate ();
Pstmt. close ();
Conn. close ();
} Catch (ClassNotFoundException e ){
E. printStackTrace ();
} Catch (SQLException e ){
E. printStackTrace ();
}
}
}
JDBCExample02.java
Code
Package com. example;
Import java. SQL .*;
Import com. mysql. jdbc. PreparedStatement;
Public class JDBCExample02 {
Public static void main (String [] args ){
String driver = "com. mysql. jdbc. Driver ";
String url = "jdbc: mysql: // localhost: 3306/work ";
String username = "root ";
String password = "";
String SQL = "select * from users ";
Try {
Class. forName (driver );
Connection conn = DriverManager. getConnection (url, username,
Password );
// Statement stat = conn. createStatement ();
PreparedStatement pstmt = (PreparedStatement) conn. prepareStatement (SQL );
ResultSet rs = pstmt.exe cuteQuery (); // call the method to obtain a ResultSet object, which is output through the while LOOP
While (rs. next ()){
System. out. println ("name:" + rs. getString ("username") + "\ tpassword:" + rs. getString ("password "));
}
Rs. close ();
Pstmt. close ();
Conn. close ();
} Catch (ClassNotFoundException e ){
E. printStackTrace ();
} Catch (SQLException e ){
E. printStackTrace ();
}
}
}
5. Execute operations
If it is implemented using oracle, the code in the add class can be changed
Code
Public static void main (String [] args ){
String driver = "oracle. jdbc. driver. Oracle ";
String url = "jdbc: oracle: thin: @ *****; 1521: ora9"; (** the IP address of the database to be connected)
String username = "";
String password = "";
String SQL = "insert into users (username, password) values (?,?) ";
}
Everything else remains unchanged. As shown in the database connection, the only difference is the use of the Driver.