在配置好数据库之后,需要测试一下能否使其与程序顺利连接
一、下载并添加数据库驱动:
下载之后,在工程中新建一个lib文件夹用于存放添加的依赖包。将jar文件放入,右键添加到项目库:
二、准备数据库连接
启动数据库服务,查看并确认数据库地址:这里注意数据库名不能弄错。填入已经准备好的假数据。
在scr文件夹中添加jdbc.properties文件,用于存放数据库的路径,用户名,密码等信息。如下:
url=jdbc:mysql://localhost:3306/sqltest?useUnicode=true&characterEncoding=utf-8
user=root
password=123456
drive=com.mysql.jdbc.Driver
三、编写获取数据库连接的类
知道了数据库信息,有了举动包之后,就可以在程序中获取数据库连接
1)获取数据库的属性:
Properties properties = new Properties();
ClassLoader classLoader = JDBCUtils.class.getClassLoader();
URL res = classLoader.getResource("jdbc.properties");
2)读取属性文件中的信息
properties.load(new FileReader(path));
url = properties.getProperty("url");
user = properties.getProperty("user");
password = properties.getProperty("password");
drive = properties.getProperty("drive");
Class.forName(drive);
3)编写连接数据库方法:
public static Connection getconnection() throws SQLException {
return DriverManager.getConnection(url,user,password);
}
4)编写关闭连接的方法:
public static void close(ResultSet rs, Statement stmt,Connection conn) {
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
四、编写登录服务方法:
获取连接之后,从数据库中读取对象,比较其密码和用户输入的密码是否一致。
public boolean login(String username ,String password){
if(username==null||password==null){return false;}
Connection connection=null;
Statement statement=null;
ResultSet resultSet =null;
try {
connection=JDBCUtils.getconnection();
String sql = " select * from jdbctable where name='"+username+"' and password = '"+password+"'";
statement=connection.createStatement();
resultSet=statement.executeQuery(sql);
return resultSet.next();
} catch (SQLException e) {
e.printStackTrace();
}
finally {JDBCUtils.close(resultSet,statement,connection);
}
return false;
}
接下来在主函数中调用login方法:
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Scanner sc =new Scanner(System.in);
System.out.println("请输入用户名:");
String username=sc.nextLine();
System.out.println("请输入密码:");
String password=sc.nextLine();
boolean loginFlag = new jdbc_test().login(username,password);
if(loginFlag){
System.out.println("登录成功");
}
else {
System.out.println("登录失败");
}
}
五、测试连接
直接运行程序,输入用户名和密码:
输错密码:
输入不存在的用户: