📄 productjdbc.java
字号:
package com.luceneheritrixbook.database;
import java.sql.*;
import com.luceneheritrixbook.core.Product;
public class ProductJDBC {
private Connection con = null;
private Statement stmt = null;
private ResultSet rs = null;
private PreparedStatement pstmt = null;
private boolean autoCommit = true;
public ProductJDBC(String url, String usr, String pwd) throws Exception {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(url, usr, pwd);
con.setAutoCommit(autoCommit);
}
public int addProduct(Product p) throws Exception {
int nextid = getNextId();
if (nextid < 0) {
throw new Exception("Can't get next id.");
}
// since we get the next id, add the info to db
String content = p.getContent();
String summary = p.getSummary();
String imageURI = p.getImageURI();
String originalUrl = p.getOriginalUrl();
String category = p.getCategory();
String name = p.getName();
String type = p.getType();
String updatedtime = p.getUpdatedtime();
String expr = "insert into product (content, abstractcontent, url, imageurl, category, name, type, updatedtime) values(?,?,?,?,?,?,?,?)";
pstmt = con.prepareStatement(expr);
pstmt.setString(1, content);
pstmt.setString(2, summary);
pstmt.setString(3, originalUrl);
pstmt.setString(4, imageURI);
pstmt.setString(5, category);
pstmt.setString(6, name);
pstmt.setString(7, type);
pstmt.setString(8, updatedtime);
pstmt.execute();
return nextid;
}
private int getNextId() throws Exception {
int result = -1;
String sql = "select max(id)+1 from product";
stmt = con.createStatement();
rs = stmt.executeQuery(sql);
while (rs.next()) {
result = rs.getInt(1);
}
return result;
}
public void close() {
if (con != null) {
try {
con.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
con = null;
}
}
}
public static void main(String[] args) {
String url = "jdbc:mysql://localhost/searchdb";
String usr = "root";
String pwd = "root";
try {
new ProductJDBC(url, usr, pwd);
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -