连接数据库的简单方法,只包含数据库相关部分代码。
——————————
1.首先加载解析驱动:
Class.forName(“com.mysql.jdbc.Driver”);//解析架包
String url = “jdbc:mysql://localhost:3306/sm17”;//路径
——————————
2.对数据库进行操作:
2.1.创建一条路,连接
Connection con = null;//创建路
con = DriverManager.getConnection(url, “root”, “137094”);//连接数据库-路
——————————
2.2.创建一个车(通过路来创建车)
Statement st=null;
st=con.createStatement();//通用的车
PreparedStatement pst=null;
pst=con.prepareStatement(sql);//专车(先给出sql)
——————————
2.3.给命令
String sql=null;//命令
sql=“select * from user where username=? and password=? and role=?”;//查询命令
——————————
2.4.结果集
ResultSet rs=null;//结果集
rs=pst.executeQuery();
案例:网页登录时的数据库查询操作:
Connection con = null;//路
Statement st=null;//车
PreparedStatement pst=null;//专车
String sql=null;//命令
ResultSet rs=null;//结果集
try {
//1.加载解析驱动包
Class.forName("com.mysql.jdbc.Driver");//解析架包
String url = "jdbc:mysql://localhost:3306/sm17";//路径
con = DriverManager.getConnection(url, "root","137094");//连接数据库-路
//2.对数据库进行操作
st=con.createStatement();//车
sql="select * from user where username=? and password=? and role=?";//给出命令
pst=con.prepareStatement(sql);//专车
pst.setString(1,un);//123代表数据库中的信息,后者代表输入的登录信息
pst.setString(2,pw);
pst.setString(3,role);
rs=pst.executeQuery();//结果集
//逻辑操作,跳转
if(rs.next())//结果集有
{
//System.out.println("登陆成功!");
int uid=rs.getInt(1); //123,"123";
String suid=Integer.toString(uid);
session.setAttribute("SID",suid);
if(role.equals("1"))
{
response.sendRedirect("shop.jsp");
}
if(role.equals("0"))
{
response.sendRedirect("main_gly.jsp?UN="+un);
}
}
else
{
//System.out.println("登陆失败 !");
response.sendRedirect("log_failure.jsp");
}
} catch (ClassNotFoundException e) {
System.out.println("驱动异常!");
} catch (SQLException e) {
System.out.println("数据库操作异常!");
} finally
{
rs.close();
pst.close();
st.close();
con.close();
}