源代码如下:
import java.sql.*;
public class ConToMySQL {
public static void main(String[] args) { //这里"liuyan"是MySql下建立的一个测试数据库 //3306是MySql数据库服务的默认端口 String url="jdbc:mysql://localhost:3306/liuyan"; String userName = "root"; String password = "yourpassword"; Connection con = null; try {//加载驱动器类
Class.forName("com.mysql.jdbc.Driver"); } catch (Exception e) { // TODO: handle exception System.out.println("加载驱动器类时出现异常"); } try {//获取数据库连接
con = DriverManager.getConnection(url,userName,password); } catch (Exception e) { // TODO: handle exception System.out.println("出现SQLException异常"); } System.out.println("加载驱动器成功"); //接着就可以操作MySql数据库了 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("写入MySQL数据库成功"); } catch (Exception e) { e.printStackTrace(); } }}