java - jdbc connection test class

   mysql create table:

    1. Import   Package

     2. Create a test class Test

    2.1  Statement attributes:

// declare a Connection object
Connection CON;
// driver name
String driver = "com.mysql.cj.jdbc.Driver"; (the new version of the driver name)
// point to the URL of the database to be accessed myWeb name and specify the time zone (I the old version zone can not use when you need to specify the version 8.0)
String url = "jdbc: MySQL: // localhost:? 3306 / myWeb serverTimezone = GMT";
the user name // MySQL configuration
String the user = "root";
/ the password / MySQL configuration
String password = "root";

2.2 to achieve a specific query table

try {

// load the driver
the Class.forName (Driver);
// 1.getConnection () method to connect MySQL database! !
DriverManager.getConnection = CON (url, the User, password);
IF (con.isClosed ()!)
System.out.println ( "Database connection success!");
// 2. Create the statement class object, used to execute SQL statements ! !
= Con.createStatement of Statement of Statement ();
// to execute SQL statements
String SQL = "the SELECT * from the Test the WHERE the above mentioned id = 33";
// 3.ResultSet class used to store the result set retrieved! !
RS = Statement.executeQuery the ResultSet (SQL);
System.out.println ( "--------------------------------- ----------------- ");
System.out.println (" execution results are shown below: ");
System.out.println (" ------- ------------------------------------------ ");
System.out.println ( "number" + "\ t" + "name" + "
System.out.println("-------------------------------------------------");

0 ID = Integer;
String name = null;
String Age = null;
String tel_phone = null;
the while (rs.next ()) {
// this column data acquisition stuname
ID = rs.getInt ( "ID");
name = RS .getString ( "name");
// this column data acquisition stuid
Age = rs.getString ( "Age");
tel_phone = rs.getString ( "tel_phone");
// output
System.out.println (id + " \ T "+ name +" \ T "+ Age +" \ T "+ tel_phone);
System.out.println (" ---------------------- -------------------------------- ");
}

rs.Close ();
con.close ();
} the catch (a ClassNotFoundException E) {
// database driver class exception handlers
System.out.println ( "Sorry, Can`t Find The driver!");
E.printStackTrace();
} catch (SQLException e) {
// database connection failure exception handling
e.printStackTrace ();
} the catch (Exception E) {
// the TODO: Exception handle
e.printStackTrace ();
} the finally {
System.out.println ( "successfully acquired data database !!") ;
}
}
3. run results:

 

 The above is a simple example of java database connection, specific comments have said very clearly, java beginner and very easy to understand, even though I was just getting started. . . Gangster want to provide more views

Guess you like

Origin www.cnblogs.com/Bury/p/10938039.html