【java基础学习】数据库编程

时间:2024-07-09 11:06:02

MySQL数据库查询

 import java.sql.*;
public class JdbcDemo1{
public static void main(String[] args){
try{
//1.加载数据库驱动程序
Class.forName("org.gjt.mm.mysql.Driver"); //2.创建与数据库的连接
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root"); //3.创建Statement对象,并执行sql语句
Statement stmt = conn.createStatement();
String sql = "select * from user";
stmt.execute(sql); //获取多个结果
ResultSet rs = stmt.getResultSet(); //4.处理结果集
while(rs.next()){
String uname = rs.getString("uname");
int age = rs.getInt("age");
System.out.println(uname + ":" + age);
} //5.关闭查询语句和连接
rs.close();
stmt.close();
conn.close();
}catch(Exception e){
e.printStackTrace();
}
}
}

主要类 Statement、ResultSet,具体方法参考jdk