java链接MySQL自己输入密码
时间: 2024-03-14 19:44:50 浏览: 19
在Java中,连接MySQL需要使用JDBC驱动程序。要连接MySQL数据库并输入密码,可以使用以下代码:
```java
import java.sql.*;
public class MySQLConnection {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "root";
String password = "";
try {
// 加载JDBC驱动程序
Class.forName("com.mysql.jdbc.Driver");
// 建立连接
Connection conn = DriverManager.getConnection(url, username, password);
// 执行查询
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM mytable");
// 处理查询结果
while (rs.next()) {
System.out.println(rs.getString("column1"));
}
// 关闭连接
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
在上面的代码中,`url`为MySQL数据库的连接字符串,`username`为用户名,`password`为密码。在建立连接时,可以使用`DriverManager.getConnection()`方法传递这些参数。
如果你不想在代码中明文输入密码,可以将密码存储在配置文件或环境变量中,并在程序运行时读取。