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 ();
}
}
}