Detailed step resolution of Java connection to mysql database

  • 2020-04-01 02:14:01
  • OfStack

< img Alt = "" border = 0 SRC =" / / files.jb51.net/file_images/article/201308/2013082609311916.jpg ">

The first step: Download a JDBC driver package, for example I used: mysql-connector-java-5.1.17-bin.jar

The second step: To import the downloaded JDBC driver package, which I used myeclipse, I selected the project I want to guide the package, right     Click on propertise, then select JavaBuild Path, libreries will appear on the right, click in, and then click Add External JARs  Then find the driver package you want to import. After that, click Order andExport, and then select the package you imported.

Step 3: Load Driver: class.forname (" com.mysql.jdbc.driver ");

Step 4: Connection database: Connection  Conn = DriverManager. GetConnection (" JDBC: mysql: / / localhost/database name ", "root", "123456");

Step 5: Declare a Statement to execute the SQL Statement: Statement STMT =conn. CreateStatement ();

Step 6: Declare a result set that catches the data executing the SQL statement :  ResultSet rs= stmt.executequery ("select * from table name ");

Here is the complete code:


 try {
   Class.forName("com.mysql.jdbc.Driver");
   System.out.println(" The test pass ");
   Connection conn=DriverManager.getConnection("jdbc:mysql://localhost/myschool","root","123456");
   System.out.println("conn-------------"+conn);
   Statement stmt=conn.createStatement();
   ResultSet rs=stmt.executeQuery("select * from admin");
   while(rs.next()){                          
    String name=rs.getString("name");
    String pwd=rs.getString("pwds");
    System.out.println("name------"+name+"--------pwd-"+pwd);
   }
  } catch (ClassNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }


Related articles: