程序功能:以mysql为例,实现查询数据库中的数据显示在java控制台中
过程如下:
1. 在MYSQL中创建表,并插入数据
create database testdb;
use testdb;
create table tb_test01(
idint primary key auto_increment,
namevarchar(40),
passwordvarchar(40),
emailvarchar(60),
birthdaydate
)character set utf8 collate utf8_general_ci;
insert into tb_test01(name,password,email,birthday) values('zs','123456','zs@sina.com','1980-12-04');
insert into tb_test01(name,password,email,birthday) values('lisi','123456','lisi@sina.com','1981-12-04');
insert into tb_test01(name,password,email,birthday) values('wangwu','123456','wangwu@sina.com','1979-12-04');
2. 创建java project项目,添加mysql的数据库驱动jar包:
3.编写jdbc操作数据库的程序;
//1、注册驱动
//2、创建连接
//3、得到执行sql语句的Statement对象
//4、执行sql语句,并返回结果
//5、处理结果
//6关闭资源
import java.sql.*;
import javax.sql.*;
public class Demo01 {
public static void main(String[] args) throws SQLException {
//1、注册驱动
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//2、创建连接
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testdb","root", "root123");
//3、得到执行sql语句的Statement对象
Statement stmt = conn.createStatement();
//4、执行sql语句,并返回结果
String url = "select * from tb_test01";
ResultSet rs = stmt.executeQuery(url);
//5、处理结果
while(rs.next()){
System.out.println(rs.getObject(1)+"|");
System.out.println(rs.getObject(2)+"|");
System.out.println(rs.getObject(3)+"|");
System.out.println(rs.getObject(4)+"|");
System.out.println(rs.getObject(5)+"|");
System.out.println("=================================");
}
//6关闭资源
rs.close();
stmt.close();
conn.close();
}
}