java连接数据库验证用户名和密码,代码
时间: 2023-06-07 19:07:59 浏览: 69
可参考如下:
```java
import java.sql.*;
public class UserLogin {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/TESTDB";
// Database credentials
static final String USER = "username";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
// Register JDBC driver
Class.forName(JDBC_DRIVER);
// Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
// Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, username, password FROM Users";
ResultSet rs = stmt.executeQuery(sql);
// Extract data from result set
while(rs.next()){
// Retrieve by column name
int id = rs.getInt("id");
String username = rs.getString("username");
String password = rs.getString("password");
// Verify username and password
if(username.equals(inputUsername) && password.equals(inputPassword)){
System.out.println("Login successful!");
break;
}
}
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
// Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
// Handle errors for Class.forName
e.printStackTrace();
}finally{
// Finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
} // nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
} // end finally try
} // end try
}
}
```
在此之前需要导入mysql的驱动包,如果无法成功连接,请检查数据库的连接信息。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)