java 连接MySql数据库

你离开我真会死。 提交于 2020-03-14 18:31:34

源代码如下:

 

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

}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!