java中怎么获取mysql数据库的数据

如题所述

用JDBC连接数据库,然后用sql语句。要导入mysql的驱动包。
import java.sql.*;

public class TestMySql {
static Connection con = null; // 声明Connection对象
static Statement sql = null;
static ResultSet res = null;

public static void main(String[] args) {
TestMySql c = new TestMySql();
con = c.getConnection();
try {
sql = con.createStatement();
res = sql.executeQuery("select * from dept");
//sql语句,我数据库里有张dept表

while (res.next()) {//输出结果
System.out.print(res.getString(1) + "<——>");
System.out.print(res.getString(2) + "<——>");
System.out.print(res.getString(3) );
System.out.println();
}

} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (res != null) {
res.close();
res =null;
}
if (sql != null) {
sql.close();
sql =null;
}
if (con != null) {
con.close();
con =null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}

}

public Connection getConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
// 加载oracleJDBC驱动
System.out.println("数据库驱动加载成功");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {// 通过访问数据库的URL获取数据库连接对象
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydata", "root", "qwer1234");
//mydata为mysql名字

System.out.println("数据库连接成功");
} catch (SQLException e) {
e.printStackTrace();
}
return con; // 按方法要求返回一个Connection对象
}

}
温馨提示:答案为网友推荐,仅供参考
相似回答