62,614
社区成员
发帖
与我相关
我的任务
分享
int count=0;//为什么validate要返回int?
class.forName("");//加载驱动类
Connection con=DriverManager.getConnection("","","");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select user from table where user="+user+" and passowrd="+password);
while(rs.next()){
//有结果
count++;
}
con.close();
return count;
"select user from table where user="+user+" and passowrd="+password
//最好把validate的返回值改为boolean
public boolean validate(){
boolean result=false;
class.forName("");//加载驱动类
Connection con=DriverManager.getConnection("","","");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select user from table where user="+user+" and passowrd="+password);
if(rs.next()){
//有结果
result=true;
}
con.close();
return result;
}
select count(*) as count from table where username = ? and password = ?
查询出来数量是否为1,为1匹配,否则不匹配import com.mysql.jdbc.Driver;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
/**
*
* @author Administrator
*/
public abstract class Database {
private static Connection connection = null;
/**
* 连接数据库
*/
public static Connection getConnect() throws SQLException, Exception {
if (connection != null && connection.isValid(1)) {
return connection;
}
// URL指向要访问的数据库名jdbc_test
String url = Config.getConfig("database.url");
// MySQL配置时的用户名
String user = Config.getConfig("database.user");
// Java连接MySQL配置时的密码
String password = Config.getConfig("database.password");
//这句可以没有
DriverManager.registerDriver(new Driver());
// 连接数据库
connection = DriverManager.getConnection(url, user, password);
connection.setAutoCommit(true);
//设置数据库的字符集
Statement statement = connection.createStatement();
statement.execute("SET character_set_client=`" + Config.getConfig("database.character_set_client") + "`");
statement.execute("SET character_set_connection=`" + Config.getConfig("database.character_set_connection") + "`");
statement.execute("SET character_set_results=`" + Config.getConfig("database.character_set_results") + "`");
statement.close();
//
return connection;
}
}
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import Database;
PreparedStatement ps = Database.getConnect().prepareStatement("select * from student order by id asc");
// 结果集
ResultSet resultSet = ps.executeQuery();
System.out.println("-----------------");
System.out.println("执行结果如下所示:");
System.out.println("-----------------");
System.out.println("id" + "\t" + "content");
System.out.println("-----------------");
while (resultSet.next()) {
// 选择sno,sname两列数据
System.out.println(resultSet.getString("id") + "\t" + resultSet.getString("content"));
}