数据库脚本:
create table account(
id int primary key auto_increment,
name varchar(40),
money float
)character set utf8 collate utf8_general_ci;
insert into account(name,money) values('aaa',1000);
insert into account(name,money) values('bbb',1000);
insert into account(name,money) values('ccc',1000);
Java代码实现:
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/mydb1", "root", "abc");
//3.获取操作数据库的预处理对象
PreparedStatement pstm = conn.prepareStatement("select * from account");
//4.执行sql,得到结果集
ResultSet rest = pstm.executeQuery();
//5.遍历结果集
while (rest.next()){
System.out.println(rest.getString("name"));
}
//6.释放资源
rest.close();
pstm.close();
conn.close();
}
本文提供了一个使用Java连接MySQL数据库并执行查询操作的具体示例。通过注册MySQL驱动,建立数据库连接,创建预处理对象执行SQL查询,并遍历结果集进行数据展示。
1070

被折叠的 条评论
为什么被折叠?



