java语言如何建立于Mysql数据库的连接

2025-04-07 19:47:15
推荐回答(1个)
回答1:

下面是一个简单的连接MySQL数据库,并操作数据库表的例子:

import java.sql.*;

public class TestMysql {

public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
//加载驱动
Class.forName("com.mysql.jdbc.Driver");
//创建连接
conn = DriverManager
.getConnection("jdbc:mysql://localhost/bbs?user=用户名&password=密码");
stmt = conn.createStatement();
rs = stmt.executeQuery("select * from user");
while (rs.next()) {
String user = rs.getString(1);
String password = rs.getString(2);
System.out.println("用户名:" + user + "," +" 密码:" + password );
}

} catch (ClassNotFoundException ex) {
ex.printStackTrace();
} catch (SQLException ex) {
ex.printStackTrace();
} finally {
try {
if (rs != null) {
rs.close();
rs = null;
}
if (stmt != null) {
stmt.close();
stmt = null;
}
if (conn != null) {
conn.close();
conn = null;
}

} catch (SQLException e) {
e.printStackTrace();
}
}
}

}

当然前提是要把MySQL的连接驱动JAR文件添加到工程里