JDBC:console控制臺實現(xiàn)插入數(shù)據(jù)到數(shù)據(jù)庫
來源:我的學習筆記

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 {
/**
* 任務(wù):使用JDBC實現(xiàn)pms數(shù)據(jù)庫中category表的數(shù)據(jù)的增加、刪除、修改、查詢操作
*/
public static void main(String[] args) {
Connection conn=null;
PreparedStatement pstmt=null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
//驅(qū)動程序全路徑? ?不用加后綴名
String url="jdbc:mysql://localhost:3306/pms?useSSL=false&&serverTimezone=UTC";? ?//關(guān)掉ssl 設(shè)置時區(qū)
//用戶名
String user="root";
//root用戶的密碼
String password="123456";
conn = DriverManager.getConnection(url,user,password);
System.out.println("請輸入你要添加的產(chǎn)品類型:");
Scanner sc=new Scanner(System.in);
int category=sc.nextInt();
System.out.println("請輸入你要添加的產(chǎn)品名字:");
String cname=sc.next();
String sql="insert into category(category,cname)values (?,?)";?
System.out.println(sql);
//3.創(chuàng)建預編譯執(zhí)行對象
pstmt=conn.prepareStatement(sql);
//給問號賦值
pstmt.setInt(1, category);
pstmt.setString(2, cname);
//執(zhí)行sql語句
int result=pstmt.executeUpdate();
//處理執(zhí)行結(jié)果
if (result>0) {
System.out.println("添加成功");
} else {
System.out.println("添加失敗");
}
//6.關(guān)閉
} 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();
}
}
}
}
}
效果圖:
