Java Connection MySQL Database

Source: Internet
Author: User

The source code is as follows:

Import java.sql.*;

public class Contomysql {
public static void Main (string[] args) {
Here "Liuyan" is a test database built under MySQL.
3306 is the default port for MySQL database service
String url= "Jdbc:mysql://localhost:3306/liuyan";
String userName = "root";
String password = "YourPassword";
Connection con = null;
try {

Load Drive Class
class.forname ("Com.mysql.jdbc.Driver");
} catch (Exception e) {
Todo:handle exception
SYSTEM.OUT.PRINTLN ("Exception occurred while loading drive class");
}
try {

Get database connection
con = drivermanager.getconnection (Url,username,password);
} catch (Exception e) {
Todo:handle exception
System.out.println ("SqlException anomaly");
}
System.out.println ("Load Drive succeeded");
Then we can operate the MySQL database.
try {
PreparedStatement prestatement = con.preparestatement ("INSERT into messages values (?,?,?,?,?)");
Prestatement.setstring (1, "TestString1");
Prestatement.setstring (2, "TestString2");
Prestatement.setdate (3, New Java.sql.Date (New Java.util.Date ()). GetTime ());
Prestatement.setstring (4, "TestString3");
Prestatement.setstring (5, "TestString4");
Prestatement.executeupdate ();
Prestatement.close ();
Con.close ();
System.out.println ("successful writing to MySQL database");
} catch (Exception e) {
E.printstacktrace ();
}
}

}

Related Article

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.