JDBC:console控制台实现插入数据到数据库
来源:我的学习笔记

package com.test0829;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;
public class h1 {
/**
* 任务:使用JDBC实现pms数据库中category表的数据的增加、删除、修改、查询操作
*/
public static void main(String[] args) {
Connection conn=null;
PreparedStatement pstmt=null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
//驱动程序全路径 不用加后缀名
String url="jdbc:mysql://localhost:3306/pms?useSSL=false&&serverTimezone=UTC"; //关掉ssl 设置时区
//用户名
String user="root";
//root用户的密码
String password="123456";
conn = DriverManager.getConnection(url,user,password);
System.out.println("请输入你要添加的产品类型:");
Scanner sc=new Scanner(System.in);
int category=sc.nextInt();
System.out.println("请输入你要添加的产品名字:");
String cname=sc.next();
String sql="insert into category(category,cname)values (?,?)";
System.out.println(sql);
//3.创建预编译执行对象
pstmt=conn.prepareStatement(sql);
//给问号赋值
pstmt.setInt(1, category);
pstmt.setString(2, cname);
//执行sql语句
int result=pstmt.executeUpdate();
//处理执行结果
if (result>0) {
System.out.println("添加成功");
} else {
System.out.println("添加失败");
}
//6.关闭
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if (pstmt!=null) {
try {
pstmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (conn!=null) {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
效果图:


