JDBC代码前编译器(IDEA)连接数据库的操作请参照我的另一篇文章
IDEA连接MySQL数据库
使用JDBC代码连接数据库有两种方式:
一、使用JDBC驱动驱动程序
public class test{
public static void main(String[] args) {
String driver="com.mysql.cj.jdbc.Driver";
String url="jdbc:mysql://localhost:3306/qzy?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT";
String user="root";
String password="root";
Connection connection = null;
Statement statement = null;
try {
Class.forName(driver);
connection = DriverManager.getConnection(url,user,password);
statement = connection.createStatement();
String sql = "insert into employee (name,age,password) values('aaa',23,'12345')";
int num = statement.executeUpdate(sql);
if (num > 0 ) {
System.out.println("注册成功");
}else {
System.out.println("注册失败");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if ( statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
其中user和password是自己安装MySQL是创建的,我在我的数据库中建立了一个database名为qzy,建立一个table名为employee用于测试,运行上面代码后增加了name为aaaa的一行数据,添加完成数据后,一定要像我的代码中一样关闭连接
不过这种方法不安全,不能防止sql注入,第二种预加载的方式会更加安全
预加载(PreparedStatement)
这一种方式不论是从安全性还是编码快捷性上都优于第一种方法
首先新建一个属性为properties的文件
这里千万记住要把这个文件放在project的src文件夹中
之后在这个文件中写入驱动信息
driverName = com.mysql.cj.jdbc.Driver
url =jdbc:mysql://localhost:3306/qzy?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT
user = root
password = root
public class connect {
private static String url;
private static String user;
private static String password;
public connect() {
}
static {
try {
Properties properties = new Properties();
properties.load(connect.class.getClassLoader().getResourceAsStream("dbconfig.properties"));
String driverName = properties.getProperty("driverName");
url = properties.getProperty("url");
user = properties.getProperty("user");
password = properties.getProperty("password");
Class.forName(driverName);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection get() {
Connection connection = null;
try {
connection = DriverManager.getConnection(url,user,password);
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
public static void close(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet){
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
这里是我写的一个连接类,可以直接调用,不用每次重复写连接代码,每次需要连接数据库就直接调用,这里也可以到处为jar包,这样在其他project中也可以使用,具体方法见我的博客其他文章。