Servlet中调用数据库

2017-01-19  本文已影响0人  8dc010427b39

Oracel

ResultSet rs = ps.executeQuery(); 

while(rs.next()){

rs.getInt(1)

rs.getString(4)

}

// 从数据库中取验证

Connection ct = null;

ResultSet rs = null;

PreparedStatement ps = null;

try {

// 1加载驱动

Class.forName("oracle.jdbc.driver.OracleDriver");

// 2得到连接

ct = DriverManager.getConnection(

"jdbc:oracle:thin:@127.0.0.1:1521:orcl", "scott", "tiger");

// 3创建PrepareStatement

ps = ct.prepareStatement("select * from users where id=? and passwd=?");

// 给?赋值

ps.setObject(1, id);

ps.setObject(2, pwd);

// 4执行操作

rs = ps.executeQuery();

// 5根据结果处理

if (rs.next()) {

// 说明该用户合法

request.getRequestDispatcher("/MainFrame").forward(request,

          response);

} else {

          request.setAttribute("errno", "用户名密码错误");

          request.getRequestDispatcher("/LoginServlet").forward(request,

response);

}

} catch (Exception e) {

e.printStackTrace();

} finally {

// 关闭资源

if (rs != null) {

try {

rs.close();

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

rs = null;

}

if (ps != null) {

try {

ps.close();

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

ps = null;

}

if (ct != null) {

try {

ct.close();

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

ct = null;

}

}

MySQL

Class.forName("com.mysql.jdbc.Driver");

Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/Chatsql","root","root");

Statement state = conn.createStatement();

String sql="select password from usr where name='"+usr+"'";

String sql2="update usr set isLogin=1 where name='"+usr+"'";

ResultSet res = state.executeQuery(sql);

while(res.next()) {

String tmp = res.getString("password");

if(tmp.equals(passwd)) {

System.out.println(usr+"登陆成功");

int count = state.executeUpdate(sql2);

System.out.println("更新了"+count+"条数据");

res.close();

state.close();

conn.close();

return true;

}

}

res.close();

state.close();

conn.close();

return false;

上一篇下一篇

猜你喜欢

热点阅读