今天又maven写了一下jdbc复习。
结果发现,怎么都运行不成功。
就在我一遍又一遍的找错之后,发现,竟然没导包,没添加依赖!!!!
共勉,一定要细心。
可能是因为,间隔时间长了,所以一开始也没注意,然后,一直不知道哪里错了。
现在上干货。
首先打开数据库,创建数据库db4.
在数据库中创建student表。
id,name,age,birthday。
分别为int,varchar,int,Date类型。
前戏做完之后。
进入正题。
首先,创建一个db.properties
在里面写入连接数据库的信息,url,driver,username,password。
即
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/db4?serverTimezone=GMT%2B8
username=root
password=root
之后,创建一个Util包,在util包里创建一个daoUtil类。
package com.bai.dao;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;
public class daoUtil {
private static String driver;
private static String url;
private static String password;
private static String username;
static {
Properties properties = new Properties();
InputStream in = daoUtil.class.getClassLoader().getResourceAsStream("db.properties");
try {
properties.load(in);
url = properties.getProperty("url");
username = properties.getProperty("username");
password = properties.getProperty("password");
driver = properties.getProperty("driver");
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection(){
Connection connection = null;
try {
Class.forName(driver);
connection = DriverManager.getConnection(url,username,password);
} catch (Exception e) {
e.printStackTrace();
}
return connection;
}
}
之后就可以,使用这个工具类了
package com.bai.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;
public class selectDao {
public static void main(String[] args) {
Connection connection = null;
PreparedStatement statement = null;
try {
connection = baseDao.getConnection();
String sql = "insert into student (id,name,age,date) values(?,?,?,?)";
statement = connection.prepareStatement(sql);
statement.setInt(1,1);
statement.setString(2,"laobai");
statement.setInt(3,20);
statement.setDate(4, new java.sql.Date(new Date().getTime()));
int i = statement.executeUpdate();
if (i>0){
System.out.println("cha ru cheng gong");
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
大概就这样。
注意,preparestatement,里的占位符,是从第一位开始的。