1.
Right-click the project (not Src) and choose -- Build Path -- Add External Archives. Select the jar package under the driver. This is the release version and the debug version under the bin directory.
The example is in connector-j.html under docs. there is an example in it (the test is the database name, which is changed to your own ).
Copy codeThe Code is as follows:
Import java. SQL. Connection;
Import java. SQL. DriverManager;
Import java. SQL. SQLException;
Connection conn = null;
...
Try {
Conn =
DriverManager. getConnection ("jdbc: mysql: // localhost/test? "+
"User = monty & password = greatsqldb ");
// Do something with the Connection
...
} Catch (SQLException ex ){
// Handle any errors
System. out. println ("SQLException:" + ex. getMessage ());
System. out. println ("SQLState:" + ex. getSQLState ());
System. out. println ("VendorError:" + ex. getErrorCode ());
}
2. You can create a database directly on the MySql console, or run "\. absolute path name ".
"--" Is a annotator.
Copy codeThe Code is as follows:
View Code
Import java. SQL. Connection;
Import java. SQL. DriverManager;
Import java. SQL. ResultSet;
Import java. SQL. SQLException;
Import java. SQL. Statement;
Public class mysql {
/**
* @ Param args
*/
Public static void main (String [] args) {// Merge multiple try values into one, and then use source --- format
// TODO Auto-generated method stub
// If finally is used, the statement must be placed outside try.
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
Try {
Class. forName ("com. mysql. jdbc. Driver"); // If ". newInstance" is added later, several throws must be added.
Conn = DriverManager. getConnection ("jdbc: mysql: // localhost/mydata? "
+ "User = root & password = root ");
/*
* Java. SQL. Statement; not the com. mysql package; both cannot exist simultaneously
*/
Stmt = conn. createStatement ();
Rs = stmt.exe cuteQuery ("select * from info ");
While (rs. next ()){
System. out. println (rs. getString ("name "));
}
// Do something with the Connection
} Catch (ClassNotFoundException ex ){
// Handle any errors
Ex. printStackTrace ();
} Catch (SQLException ex ){
// TODO Auto-generated catch block
System. out. println ("SQLException:" + ex. getMessage ());
System. out. println ("SQLState:" + ex. getSQLState ());
System. out. println ("VendorError:" + ex. getErrorCode ());
} Finally {
Try {
If (null! = Rs ){
Rs. close ();
Rs = null;
}
If (null! = Stmt ){
Stmt. close ();
Stmt = null;
}
If (null! = Conn ){
Conn. close ();
Conn = null;
}
} Catch (SQLException e ){
E. printStackTrace ();
}
}
}
}