JDBC的基本步骤
- 初始化一个DataSource
- 通过DataSource获取Connection
- 不停得循环执行sql
1.通过Connection获取PrepareStatement
2.通过setXXX系列操作填充PrepareStatement中的占位符
3.根据有没有结果分别执行executeQurey或者executeUpdate
4.通过ResultSet获取结果信息
5.关闭所有资源(建议使用try—with—resource) - 关闭连接(建议使用try—with—resource)
//通过DataSource获取Connection
public class DBUtil {
private static DataSource dataSource = null;
public static void initDataSource() {
MysqlDataSource mysqlDataSource = new MysqlDataSource();
mysqlDataSource.setServerName("127.0.0.1");
mysqlDataSource.setPort(3306);
mysqlDataSource.setUser("root");
mysqlDataSource.setPassword("bnn19961006");
mysqlDataSource.setDatabaseName("boke");
mysqlDataSource.setUseSSL(false);
mysqlDataSource.setCharacterEncoding("utf8");
dataSource = mysqlDataSource;
}
public static Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
}
//连接后实现博客系统的发表文章功能
if(User.isLoginned()) {
Scanner scan = new Scanner(System.in);
System.out.print("请输入文章标题> ");
String title = scan.nextLine();
System.out.print("请输入文章内容> ");
String content = scan.nextLine();
int author_id = User.getCurrentUser().id;
Date published_at = new Date();
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String publishedatstr = format.format(published_at);
try(Connection c = DBUtil.getConnection()) {
String sql = "insert into articles (author_id,title,content,published_at) values (?,?,?,?)";
try(PreparedStatement s = c.prepareStatement(sql)) {
s.setInt(1,author_id);
s.setString(2,title);
s.setString(3,content);
s.setString(4,publishedatstr);
s.executeUpdate();
System.out.println("发表成功");
}
} catch (SQLException e) {
e.printStackTrace();
}
} else {
System.out.println("您还没有登录");
}