3-2 自由编程 作业
来源:3-2 自由编程
csm032
2020-04-22 16:43:28
JAVA部分——
package com.imooc.jdbc.demo1;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.junit.Test;
public class Lianxi_3_2 {
@Test
public void demo(){
Connection conn=null;
Statement stmt=null;
ResultSet rs=null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbctest1?serverTimezone=Hongkong", "root", "123456");
String sql1="insert goods values(null,'耳机',200.0,'蓝牙耳机')";
stmt=conn.createStatement();
int i=stmt.executeUpdate(sql1);
if(i>0) {
System.out.println("添加数据成功!");
}
String sql2="select * from goods";
rs=stmt.executeQuery(sql2);
while(rs.next()) {
int id=rs.getInt("id");
String name=rs.getString("name");
String price=rs.getString("price");
String desp=rs.getString("desp");
System.out.println(id+" "+name+" "+price+" "+desp);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(rs!=null) {
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
rs=null;
}
if(stmt!=null) {
try {
stmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
stmt=null;
}
if(conn!=null) {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
conn=null;
}
}
}
}MySQL部分——
create database jdbctest1;
use jdbctest1;
create table goods(
id int unsigned key auto_increment,
name varchar(20) not null,
price float not null,
desp varchar(30) not null
);
insert goods(name,price,desp) values('手机',2000.0,'黑色,存储容量32G'),
('冰箱',1500.0,'银色,对开门'),
('洗衣机',3000.0,'滚筒'),
('空调',4000,'变频空调');
select * from goods;
1回答
同学你好!程序运行效果正确,完成得很好!继续加油。
如果我的回答解决了你的疑惑,请采纳,祝学习愉快~
相似问题