java 操作mysql表
今天要根据动态的数据库名字创建和删除表,结果一直提示sql语句显示错误,搞了很久。下面直接上正确代码:
public void dropTable(String DB){
try {
//判断数据库中是否存在表
pstmt = conn.prepareStatement("SELECT table_name FROM information_schema.TABLES WHERE table_name =?");
pstmt.setString(1, DB);
rs = pstmt.executeQuery();
if(rs.next()){//如果存在则删除
pstmt = conn.prepareStatement("drop table "+DB);
pstmt.execute();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void updateTable(String DB) {
try {
pstmt = conn.prepareStatement("SELECT table_name FROM information_schema.TABLES WHERE table_name =?");
pstmt.setString(1, DB);
rs = pstmt.executeQuery();
if(rs.next()==false){
pstmt = conn.prepareStatement("CREATE TABLE "+DB+" ( id int ,productName varchar(45) ,pageNum int ,locationH varchar(25) ,locationV varchar(25),detailMsg varchar(100) ) ");
pstmt.execute();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
产生错误的原因是:我在红色的地方是用占位符的,改成上面的那样才正确。
补充:软件开发 , Java ,