eclipse連結資料庫mysql登陸
阿新 • • 發佈:2018-12-12
連結資料庫類
package com;
import java.sql.*;
public class Mydb
{
Connection conn=null;
Statement stmt=null;
ResultSet rs=null;
public Mydb()
{
try
{
Class.forName("com.mysql.jdbc.Driver");//找驅動物件 找不到報異常
}
catch(Exception e){e.printStackTrace();}
String url="jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=gbk";
String user="root";
String password="123456";
try
{
conn=DriverManager.getConnection(url,user,password);
}
catch(SQLException e){e.getMessage();}
}
public ResultSet query(String sql)
{
try
{
stmt=conn.createStatement();
rs=stmt.executeQuery(sql);
}
catch(Exception e){e.getMessage();}
return rs;
}
public void update(String sql)//void可以不往回傳引數
{
try
{
stmt=conn.createStatement();
stmt.executeUpdate(sql);
}
catch(Exception e){e.getMessage();}
}
public void Close(){
if(conn!=null){
try{
conn.close();
}
catch(SQLException e){
e.printStackTrace();
}
}
}
}
check
package Bean;import com.Mydb;
import java.sql.*;
public class Check
{
public boolean isLogin(String xh,String mm)
{
String a=null;
String b=null;
try
{
ResultSet rs=null;
Mydb db=new Mydb();
a=xh;
b=mm;
String str="select * from xs where xh='"+a+"' and mm='"+b+"'";
rs=db.query(str);
System.out.print(str);
if(rs.next()){
rs.getString("xh");
db.Close();
return true;}
}
catch(Exception e){e.printStackTrace();}
return false;
}
}
action
package com;import Bean.Check;
public class LoginAction
{
private String xh;
private String mm;
public String getXh() {
return xh;
}
public void setXh(String xh) {
this.xh = xh;
}
public String getMm() {
return mm;
}
public void setMm(String mm) {
this.mm = mm;
}
public String execute()
{
Check c=new Check();
if(c.isLogin(getXh(), getMm()))
return "success";//返回struts中
else
return "failure";
}
}
jsp頁面
<%@ page language="java" contentType="text/html; charset=GB18030"
pageEncoding="GB18030"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>Insert title here</title>
</head>
<body>
<form action="login.action">
使用者名稱:<input type="text" name="xh"><br>
密碼:<input type="text" name="mm"><br>
<input type="submit" value="登入">
</form>
</body>
</html>