mysql怎么和eclipse连接

如题所述

mysql和eclipse连接参考下面代码
import java.sql.*;

publicclass MysqlJdbc {
publicstaticvoid main(String args[]) {
try {
Class.forName("com.mysql.jdbc.Driver"); //加载MYSQL JDBC驱动程序
//Class.forName("org.gjt.mm.mysql.Driver");
System.out.println("Success loading Mysql Driver!");
}
catch (Exception e) {
System.out.print("Error loading Mysql Driver!");
e.printStackTrace();
}
try {
Connection connect = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test","root","198876");
//连接URL为 jdbc:mysql//服务器地址/数据库名 ,后面的2个参数分别是登陆用户名和密码

System.out.println("Success connect Mysql server!");
Statement stmt = connect.createStatement();
ResultSet rs = stmt.executeQuery("select * from user");
//user 为表的名称
while (rs.next()) {
System.out.println(rs.getString("name"));
}
}
catch (Exception e) {
System.out.print("get data error!");
e.printStackTrace();
}
}
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2017-03-21
没学过 jdbc?
private static final String DRIVER = "com.mysql.jdbc.Driver";
private static final String URL = "jdbc:mysql://localhost:3306/gymrent?characterEncoding=utf-8";
private static final String NAME = "root";
private static final String PASSWORD = "123456";
/**
* 与数据库建立连接
*
* @return Connection对象
*/
private Connection getConn() {
Connection conn = null;
try {
Class.forName(DRIVER);//注册(加载)驱动
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
conn = DriverManager.getConnection(URL,NAME,PASSWORD);//获得数据库连接
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}

/**
* 释放你所传过来的资源对象
*
* @param rs
* @param pstmt
* @param conn
*/
private void closeAll(ResultSet rs, PreparedStatement pstmt, Connection conn) {
try {
if (rs != null) {
rs.close();
}
if (pstmt != null) {
pstmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}