try{
Class.forName("com.mysql.jdbc.Driver");
String strUrl = "jdbc:mysql://localhost:3306/sys";
String strUser = "root";
String strPass = "123456";
Connection conn = DriverManager.getConnection(strUrl,strUser,strPass);
if( conn != null ){
Statement stat = conn.createStatement();
//创建数据库
stat.executeUpdate("create database IF NOT EXISTS db_bookinfo");
//打开创建的数据库
stat.close();
conn.close();
strUrl = "jdbc:mysql://localhost:3306/db_bookinfo";
conn = DriverManager.getConnection(strUrl,strUser,strPass);
stat = conn.createStatement();
stat.executeUpdate("create table IF NOT EXISTS db_bookinfo(id int,name varchar(125),author varchar(125),price double)");
String strSql = "insert into db_bookinfo(id,name,author,price) values(?,?,?,?)";
PreparedStatement ps = conn.prepareStatement(strSql);
ps.setInt(1,book.getId());
ps.setString(2,book.getName());
ps.setString(3,book.getAuthor());
ps.setDouble(4,book.getPrice());
int nRow = ps.executeUpdate();
if(nRow > 0) {
out.print("成功添加了 " + nRow + "条记录");
}
ps.close();
conn.close();
}
}
catch (Exception e){
out.print("添加图书信息失败!");
e.printStackTrace();
}
JSP 创建数据库,写数据的例子