老师,检查作业!

来源:2-11 自由编程

BirdMan98

2020-02-06 18:27:49

package com.zj.jdbc.demo;


import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;


import org.junit.jupiter.api.Test;


import com.mysql.jdbc.Connection;

import com.mysql.jdbc.Statement;


public class JDBCDemo {

@Test

public void demo() {

Connection connection = null;

Statement statement = null;

ResultSet resultSet = null;

try {

Class.forName("com.mysql.jdbc.Driver");//注册驱动

//获取链接

connection = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/test"+"?useUnicode=true&characterEncoding=utf-8","root","root");

String sql = "select * from goods where price < 3500";

statement = (Statement) connection.createStatement();

resultSet = statement.executeQuery(sql);//执行sql语句

while (resultSet.next()) {

int id = resultSet.getInt("id");

String name = resultSet.getString("name");

String desp = resultSet.getString("desp");

float price = resultSet.getFloat("price");

System.out.println(id+" "+name+" "+price+" "+desp);

}

} catch (Exception e) {

e.printStackTrace();

} finally {

if (statement!=null) {

try {

statement.close();

} catch (SQLException e) {

e.printStackTrace();

}

statement = null;

}

if (connection!=null) {

try {

connection.close();

} catch (SQLException e) {

e.printStackTrace();

}

connection = null;

}

if (resultSet!=null) {

try {

resultSet.close();

} catch (SQLException e) {

e.printStackTrace();

}

resultSet = null;

}

}

}

}

http://img.mukewang.com/climg/5e3be9fd09880ea906330315.jpg

http://img.mukewang.com/climg/5e3bea22099fbe6706800182.jpg

写回答

1回答

好帮手慕珊

2020-02-06

同学,你好!程序运行效果正确,符合作业要求,整体完成得非常好!

有个小问题:Statment和Connection可以不用进行类型转换,同学导入包的时候有误。如下图所示,被注释的类是同学导入的,上面未注释的才是应该导入的类。

http://img.mukewang.com/climg/5e3bf55d092b25cc05500158.jpg

如果我的回答解决了你的疑惑,请采纳!祝学习愉快!

0

0 学习 · 8016 问题

查看课程