jsp和MySQL数据库的连接
可以通过一个函数来实现数据库的连接,简化代码:
代码如下:
package data;
import java.sql.*;
import java.text.SimpleDateFormat;
public class DataConn {
/为数据库的连接赋值,userName表示数据库的用户名,userPassword代表用户密码,DBName表示数据表/
public static Connection getConn(String userName, String userPassword, String dbName) {
String driver = “com.mysql.jdbc.Driver”;
String url=”jdbc:mysql://localhost/”+dbName+”?user=”+userName+”&password=”+userPassword;
Connection conn = null;
try {
Class.forName(driver);
conn = DriverManager.getConnection(url);
}catch(ClassNotFoundException e) {
e.printStackTrace();
}catch(SQLException e2) {
e2.printStackTrace();
}
return conn;
}
/执行数据库语句的类型/
public static Statement getStatement(Connection conn) {
Statement stmt = null;
try {
if(conn!=null) {
stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
}
}catch(SQLException e3) {
e3.printStackTrace();
}
return stmt;
}
/*返回数据库语句执行的结果集*/
public static ResultSet getResultSet(Statement stmt, String sql) {
ResultSet rs = null;
if(stmt!=null) {
try{
rs = stmt.executeQuery(sql);
}catch(SQLException e4) {
e4.printStackTrace();
}
}
return rs;
}
public static String toStrChnYmdHms(Timestamp timestamp) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
return sdf.format(timestamp);
}
}