jdbc连接测试
在配置好数据库之后,需要测试⼀下能否使其与程序顺利连接
⼀、下载并添加数据库驱动:
下载之后,在⼯程中新建⼀个lib⽂件夹⽤于存放添加的依赖包。将jar⽂件放⼊,右键添加到项⽬库:
⼆、准备数据库连接
启动数据库服务,查看并确认数据库地址:这⾥注意数据库名不能弄错。填⼊已经准备好的假数据。
在scr⽂件夹中添加jdbc.properties⽂件,⽤于存放数据库的路径,⽤户名,密码等信息。如下:
url=jdbc:mysql://localhost:3306/sqltest?useUnicode=true&characterEncoding=utf-8
user=root
password=123456
sql.jdbc.Driver
三、编写获取数据库连接的类
知道了数据库信息,有了举动包之后,就可以在程序中获取数据库连接
1)获取数据库的属性:
Properties properties =new Properties();
ClassLoader classLoader = ClassLoader();
URL res = Resource("jdbc.properties");
2)读取属性⽂件中的信息
properties.load(new FileReader(path));
url = Property("url");
user = Property("user");
password = Property("password");
drive = Property("drive");
Class.forName(drive);
3)编写连接数据库⽅法:
public static Connection getconnection()throws SQLException {
Connection(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){
mysql下载之后是个文件夹
if(username==null||password==null){return false;}
Connection connection=null;
Statement statement=null;
ResultSet resultSet =null;
try{
nection();
String sql =" select * from jdbctable where name='"+username+"' and password = '"+password+"'";            ateStatement();
uteQuery(sql);
();
}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 Line();
System.out.println("请输⼊密码:");
String Line();
boolean loginFlag =new jdbc_test().login(username,password);
if(loginFlag){
System.out.println("登录成功");
}
else{
System.out.println("登录失败");
}
}
五、测试连接
直接运⾏程序,输⼊⽤户名和密码:
输错密码:
输⼊不存在的⽤户:

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。