连接方法:
1. 在MyEclipse中导入MySQL的JDBC驱动包(mysql-connector-java-5.1.5-bin.jar);
2.驱动程序:com.mysql.jdbc.Driver
3.连接地址:jdbc:mysql://localhost/数据库名?user=用户名&password=密码
实例:
实例:
TestMySQLConnection.java:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class TestMySQLConnection {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
String sql = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/mgc?user=root&;password=admin");
stmt = conn.createStatement();
sql = "Select * FROM member";
rs = stmt.executeQuery(sql);
while (rs.next()) {
System.out.println(rs.getInt("id") + "," + rs.getString("name") + "," + rs.getInt("age"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.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();
}
}
}
}
本文提供了一个使用MyEclipse连接MySQL数据库的示例代码。通过导入MySQL的JDBC驱动包并在Java程序中加载驱动程序,可以实现与本地MySQL数据库的连接,并执行SQL查询语句获取数据。

8373

被折叠的 条评论
为什么被折叠?



