连接Mysql数据库

1.将jdbc驱动加入项目

如果想要连接Mysql数据库,首先就得在该项目里面加入jdbc驱动。右击你的项目,再点击Build Path,然后点击Add External,将你的驱动加入了项目中。

2.注入jdbc驱动(关键代码)

 Class.forName("com.mysql.jdbc.Driver");

3.连接数据库

connection = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/testjdbc","root","root");  
   //其中testjdbc为数据库名,root分别为用户名与密码。

4.判断数据库是否连接上

//直接在
connection = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/testjdbc","root","root");
//后面输出一句话就行
System.out.println("数据库连接成功!");

5.编写sql语句

//如插入语句:
String sql="insert into test(id,username,password,sex) values(0,"张三","123","男")";

6.创建PreparedStatement对象

PreparedStatement ps = (PreparedStatement) connection.prepareStatement(sql);

7.执行sql语句

ps.execute();
posted @ 2019-05-22 20:51  荏苒时光  阅读(187)  评论(0编辑  收藏  举报