Connect Java to mysql database and javamysql Database
1. Create a Java project testMysql (intellij editor is used ).
2. Import the mysql driver package.
(1)
(2)
(4)
3. write code
Import java. SQL. Connection;
Import java. SQL. DriverManager;
Import java. SQL. SQLException;
/**
* Created by wuy on 2015/7/24.
*/
Public class testMysql {
Private Connection con;
Private String user = "root ";
Private String password = "root ";
Private String className = "com. mysql. jdbc. Driver ";
Private String url = "jdbc: mysql: // 127.0.0.1: 3306/goods ";
Public testMysql (){
Try {
Class. forName (className );
System. out. println ("database driver loaded successfully! ");
} Catch (ClassNotFoundException e ){
System. out. println ("failed to load the database driver! ");
E. printStackTrace ();
}
}
/** Create a database connection */
Public Connection getCon (){
Try {
Con = DriverManager. getConnection (url, user, password );
System. out. println ("database connection created successfully! ");
} Catch (SQLException e ){
System. out. print (con );
System. out. println ("An error occurred while creating the database connection! ");
Con = null;
E. printStackTrace ();
}
Return con;
}
Public void closed (){
Try {
If (con! = Null ){
Con. close ();
}
} Catch (SQLException e ){
System. out. println ("failed to close con object! ");
E. printStackTrace ();
}
}
Public static void main (String [] args)
{
TestMysql c = new testMysql ();
C. getCon ();
C. closed ();
}
}
4. Running result