在MySQL中建立user表,插入数据
create table user(
id int,
name varchar(10),
age int
)engine myisam charset utf8; insert into user(id,name,age) values
(1,'zhang',18),
(2,'lisi',20),
(3,'laowang',30);
新建java工程,导入驱动jar包
java类
package com.itheima.domain; import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement; public class JDBCTest {
public static void main(String[] args) throws Exception {
//1,加载驱动程序
Class.forName("com.mysql.jdbc.Driver");
//2,链接数据库
Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/qq","root","111111");
//3,得到发送查询语句的对象
Statement stmt=conn.createStatement();
//4,发送语句
String sql="select id,name,age from user";
ResultSet rs=stmt.executeQuery(sql);
//5,打印
while(rs.next()){
System.out.print("id号:"+rs.getInt("id"));
System.out.print("姓名:"+rs.getString("name"));
System.out.println("年龄:"+rs.getInt("age"));
}
//6释放资源
rs.close();
stmt.close();
conn.close(); } }
运行结果:
id号:1姓名:zhang年龄:18
id号:2姓名:lisi年龄:20
id号:3姓名:laowang年龄:30