62,621
社区成员
发帖
与我相关
我的任务
分享
import java.sql.*; //导入操作数据库所需的包
public class TestMySqlConnect {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver"); //载入mysql驱动程序
conn = DriverManager
.getConnection("jdbc:mysql://localhost/mydata?user=root&password=6656565");//建立数据库连接
stmt = conn.createStatement();//创建状态
rs = stmt.executeQuery("select * from dept");//执行SQL语句,返回值放到ResultSet集合中
while (rs.next()) { //获取结果集中的内容
System.out.println(rs.getString("deptno"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (conn != null) {
conn.close();conn = null; //关闭连接
}
if (stmt != null) {
stmt.close();stmt = null; //释放资源
}
if (rs != null) {
rs.close();rs = null; //释放资源
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}