java连接mysql
时间: 2023-07-11 17:16:29 浏览: 49
要使用Java连接MySQL,需要按照以下步骤进行操作:
1. 下载并安装MySQL Connector/J驱动程序。
2. 在Java程序中,使用以下代码进行连接:
```
import java.sql.*;
public class ConnectMySQL {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/mydatabase";
String user = "myuser";
String password = "mypassword";
try {
Connection conn = DriverManager.getConnection(url, user, password);
System.out.println("Connected to the database.");
} catch (SQLException e) {
System.out.println("Failed to connect to the database.");
e.printStackTrace();
}
}
}
```
其中,url是数据库的地址,mydatabase是数据库的名称,myuser是用户名,mypassword是密码。
3. 在Java程序中,使用Statement对象或PreparedStatement对象执行SQL语句。
```
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM mytable");
PreparedStatement pstmt = conn.prepareStatement("INSERT INTO mytable(name, age) VALUES(?, ?)");
pstmt.setString(1, "John");
pstmt.setInt(2, 25);
pstmt.executeUpdate();
```
这些代码示例只是简单的演示,在实际应用中需要根据具体情况进行调整和优化。