javabean怎样连接到数据库?
发布网友
发布时间:2022-04-29 01:54
我来回答
共1个回答
热心网友
时间:2022-06-28 02:27
//这是能够正确运行的javaBean
package book;
import java.sql.*;
public class notebook{
String sDBDriver = "org.gjt.mm.mysql.Driver";
String sConnStr = "jdbc:mysql://localhost/notebook?user=root&password=admin&useUnicode=true&characterEncoding=8859_1";
Connection conn = null;
ResultSet rs = null;
public notebook() throws SQLException{
try
{
Class.forName(sDBDriver);
}
catch(java.lang.ClassNotFoundException e)
{
System.err.println( e.getMessage());
}
}
public ResultSet executeQuery(String sql) {
rs = null;
try
{
conn = DriverManager.getConnection(sConnStr);
Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
rs = stmt.executeQuery(sql);
}
catch(SQLException ex)
{
System.err.println(ex.getMessage());
}
return rs;
}
//定义executeUpdate方法
public void executeUpdate(String sql) {
try
{
conn = DriverManager.getConnection(sConnStr);
Statement stmt = conn.createStatement();
stmt.executeUpdate(sql);
stmt.executeUpdate(sql);
stmt.close();
conn.close();
}
catch(SQLException ex)
{
System.err.println("aq.executeUpdate: " + ex.getMessage());
System.err.println("aq.executeUpadatestrSQL: " + sql);
}
}
}