连接方法:
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();
}
}
}
}