Java Web连接数据库——简单的Jsp连接数据库

连接数据库的简单方法,只包含数据库相关部分代码。
——————————

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();
	    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值