登录 之 服务端响应(三)
ConnectionPool.getInstance();
conn=connpool.getConnection();
try {
pstmt = conn.prepareStatement("select * from Student where SAccounts = and SPasswd = ;");
pstmt.setString(1, name);
pstmt.setString(2, passwd);
rs = pstmt.executeQuery();
if(rs.next()){
return true;
}else return false;
} catch (SQLException e) {
e.printStackTrace();
} finally {
connpool.releaseConnection(conn);
}
return false;
}
private ResultSet getLogOnUserInfo(){
return this.rs;
}
private boolean validateUserExist(String name){
connpool=ConnectionPool.getInstance();
conn=connpool.getConnection();
try {
pstmt = conn.prepareStatement("select * from Student where SAccounts = ;");
pstmt.setString(1, name);
rs = pstmt.executeQuery();
if(rs.next()){
return true;
}else return false;
} catch (SQLException e) {
e.printStackTrace();
} finally {
connpool.releaseConnection(conn);
}
return false;
}
private boolean registerUserInfo(String name,String passwd){
connpool=ConnectionPool.getInstance();
conn=connpool.getConnection();
try {
pstmt = conn.prepareStatement("insert into Student(SID,SName,SAccounts,SPasswd) values( , , , );");
pstmt.setString(1, "id_"+name);
pstmt.setString(2, "test_"+name);
pstmt.setString(3, name);
pstmt.setString(4, passwd);
int rows=pstmt.executeUpdate();
if(rows != 0){
}else {
return false;
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
connpool.releaseConnection(conn);
}
return false;
}
public static void main(String[] args) throws IOException {
NioServer ns = new NioServer();
ns.BuildNioServer();
}
}
为了提高
数据库的连接性能,所以采用了连接池的设计:
定义连接池接口:ConnectionPoolInterface.java
[java]
package com.net;
import java.sql.Connection;
public interface ConnectionPoolInterface {
public Connection getConnection();
public void releaseConnection(Connection con);
}
实现连接代理:ConnectionHandler.java
[java]
package com.net;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
public class ConnectionHandler implements InvocationHandler {
private Connection con;
private ConnectionPool pool;
public ConnectionHandler(ConnectionPool pool) {
this.pool = pool;
}
public Connection bind(Connection con) {
this.con = con;
// Connection proxyCon = (Connection) Proxy.newProxyInstance(con
// .getClass().getClassLoader(), con.getClass().getInterfaces(),
// this);
Connection proxyCon = (Connection) Proxy.newProxyInstance(
Connection.class.getClassLoader(),