Connect Java to mysql database and javamysql Database

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.