Basic steps for Java and MySQL links:
First Step: Register driver
Method One:
[Java]View PlainCopy
- Drivermanager.registerdriver (new Com.mysql.jdbc.Driver ());
Method Two: Set properties
[Java]View PlainCopy
- System.setproperty ("Jdbc.drivers", "Com.mysql.jdbc.Driver");
Method Three:
[Java]View PlainCopy
- Class.forName ("Com.mysql.jdbc.Driver");
Step two: Establish a connection
[Java]View PlainCopy
- Connection conn = (Connection) drivermanager.getconnection ("Jdbc:mysql://localhost:3306/test", "root", " Root ");
Step three: Create a statement
[Java]View PlainCopy
- Statement st = (Statement) conn.createstatement ();
Fourth step: Execute the statement
Fifth step: Process the results
Sixth step: Freeing up resources
Test code:
[Java]View PlainCopy
- Import Java.sql.DriverManager;
- Import Java.sql.ResultSet;
- Import java.sql.SQLException;
- Import com.mysql.jdbc.Connection;
- Import com.mysql.jdbc.Statement;
- Public class Demo {
- public static void Main (string[] args) {
- Demo d = new demo ();
- try {
- D.test ();
- } catch (SQLException e) {
- //TODO auto-generated catch block
- E.printstacktrace ();
- }
- }
- static void Test () throws SQLException {
- //First step: Register driver
- Drivermanager.registerdriver (new Com.mysql.jdbc.Driver ());
- ///Step two: Establish a connection
- Connection conn = (Connection) drivermanager.getconnection ("Jdbc:mysql://localhost:3306/test", "root", " Root ");
- //Step three: Create a statement
- Statement st = (Statement) conn.createstatement ();
- //Fourth step: Execute the statement and remove the result
- ResultSet rs = st.executequery ("select * from MyTable");
- //Fifth step: Process results
- While (Rs.next ()) {
- System.out.println (Rs.getobject (1) + "\ T" + Rs.getobject (2) + "\ T"
- + Rs.getobject (3));
- }
- //Sixth step: Release Resources
- Rs.close ();
- St.close ();
- Conn.close ();
- }
- }
Basic steps for Java JDBC to connect to MySQL