<span style="font-size:24px;"> <% try{ Class.forName("com.mysql.jdbc.Driver"); Connection cnt=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/huayu","root",""); } catch(ClassNotFoundException e){ out.print("找不到驱动泪"); } catch(SQLException e){ out.print("连接mysql失败"); } %></span>
jsp连接mysql数据库
语句对象statement可以用来执行sql语句,从而实现数据库操作,可以通过调用连接对象createStatement()方法来创建并获得语句对象
这个对象主要包括两个方法 executeUpdate()方法和executeQuery()主要用来执行数据库
jsp向数据库加入一条记录
<% Connection cnt=null; try{ Class.forName("com.mysql.jdbc.Driver"); cnt=DriverManager.getConnection("jdbc:mysql://localhost:3306/huayu","root",""); } catch(ClassNotFoundException e){ out.print("找不到驱动泪"); } catch(SQLException e){ out.print("连接mysql失败"); } try{ //创建语句对象 Statement stmt=cnt.createStatement(); //添加一条用户信息 String add="insert into student values('aa','ss','ss',24,'ss','ss')"; stmt.executeUpdate(add); } catch(SQLException e){ out.print("添加用户失败"); } %>ResultSet结果集
ResultSet结果集对象包含了所有查询得到的记录。可以通过Resultset的next()方法来获得一笔一笔的数据
<% Connection cnt=null; ResultSet rs=null; Statement stmt=null; try{ Class.forName("com.mysql.jdbc.Driver"); cnt=DriverManager.getConnection("jdbc:mysql://localhost:3306/huayu","root",""); //创建语句对象 stmt=cnt.createStatement(); String add="select * from student"; rs=stmt.executeQuery(add); while(rs.next()){ String userid=rs.getString(1); out.println(userid); } } catch(ClassNotFoundException e){ out.print("找不到驱动泪"); } catch(SQLException e){ out.print("连接mysql失败"); } finally{ if(rs!=null){ rs.close(); } if(stmt!=null){ stmt.close(); } if(cnt!=null){ cnt.close(); } } %>