文章标题

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);
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值