默认:
mysql的Driver的全名:com.mysql.jdbc.Driver
private String url = "jdbc:mysql://localhost:3306/Learn?useUnicode=true&characterEncoding=utf-8";
其中Learn 表示MySQL中新建的数据库名。
JAVA代码如下:
package com.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class JdbcDemo {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/learn?useUnicode=true&characterEncoding=utf-8";
// 1、加载驱动
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
// 2、获取连接
try {
// 第一个参数:需要连接的数据库地址,数据库名...
// 第二个参数:用户名
// 第三个参数:密码
Connection conn = DriverManager.getConnection(url, "root", "123456");
// 增加
String sql = "insert into student_info(name,sex,birthday,score) " + "values('Study','0','2019-11-22',88)";
// 通过Connection创建一个PreparedStatement对象
PreparedStatement pst = conn.prepareStatement(sql);
// 执行sql语句(增删改)
pst.executeUpdate();
// 删除
sql = "delete from student_info where id=1";
pst = conn.prepareStatement(sql);
pst.executeUpdate();
// 修改
sql = "update student_info set name='啼',sex=1 where id=2";
pst = conn.prepareStatement(sql);
pst.executeUpdate();
// 动态赋值
String name = "Hello";
String sex = "1";
String birthday = "2018-12-12";
double score = 99;
sql = "insert into student_info(name,sex,birthday,score) values(?,?,?,?)";
pst = conn.prepareStatement(sql);
pst.setString(1, name);
pst.setString(2, sex);
pst.setString(3, birthday);
pst.setDouble(4, score);
pst.executeUpdate();
// 最后
pst.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
JDBC连接另外需要导入的外部jar包如下:
链接:https://pan.baidu.com/s/1klcbxJvpS6IpGGC6PbwKFA
提取码:ysca
MySQL使用的安装即其使用的图形界面(二者版本要求能协调使用,我这边版本较低,但不影响使用)如下:
链接:https://pan.baidu.com/s/1frKT7kSKR6n8lNNBuir3Lg
提取码:wugt
Navicat直接解压后即可使用,内部的 sn.txt 为注册码。
MySQL直接傻瓜式安装,记住自己设置的密码,选择utf-8编码格式即可。
MySQL密码忘记也不用卸载再重装,参考如下:
https://jingyan.baidu.com/album/454316ab4e9e65f7a7c03ad1.html?picindex=3
通过命令修改。