JDBC-SqlServer增刪改查例子
阿新 • • 發佈:2019-01-05
SqlServer增刪改查例子
這是之前做過的,當時學校教的微軟的SqlServer2008,所以資料庫是這個,但是大同小異,
目前我使用MySql,以下程式碼是連線SqlServer2008的。
前提:
下載好相應版本的驅動jar包 下載連結http://download.csdn.net/detail/acm_th/9190425
程式碼如下:
package com.example.homework;
import java.sql.*;
//定義介面
interface SqlInter {
void insertData(String name, String note, float price, int amount); //插入資料方法
void updateData(String name, int pid); // 更新資料方法
void deleteData(int pid); // 刪除資料方法
void queryData(); // 查詢資料方法
}
public class SqlDemo implements SqlInter {
private PreparedStatement pstat = null;
private ResultSet rs = null;
private String forname = "com.microsoft.sqlserver.jdbc.SQLServerDriver" ;
private String getConnection = "jdbc:sqlserver://127.0.0.1:1433;DatabaseName=product";
private String admin = "sa";
private String pass = "123456";
private Connection con = null;
public SqlDemo() {
try {
Class.forName(forname);// 載入驅動器
con = DriverManager.getConnection(getConnection, admin, pass);
} catch (Exception e) {
e.printStackTrace();
}
}
// 刪除資料
public void deleteData(int pid) {
try {
String seek = "DELETE Product WHERE pid = ?";
pstat = con.prepareStatement(seek);
pstat.setInt(1, pid);
int res = pstat.executeUpdate();
System.out.println(res > 0 ? "刪除成功" : "刪除失敗");
} catch (Exception e) {
e.printStackTrace();
}
}
// 更新資料
public void updateData(String name, int pid) {
try {
String seek = "UPDATE Product SET name = ? WHERE pid = ?";
pstat = con.prepareStatement(seek);
pstat.setString(1, name);
pstat.setInt(2, pid);
int res = pstat.executeUpdate();
System.out.println(res > 0 ? "更新成功" : "更新失敗");
} catch (Exception e) {
e.printStackTrace();
}
}
// 插入資料
public void insertData(String name, String note, float price, int amount) {
try {
String seek = "INSERT Product VALUES (?, ?, ?, ?)";
pstat = con.prepareStatement(seek);
pstat.setString(1, name);
pstat.setString(2, note);
pstat.setFloat(3, price);
pstat.setInt(4, amount);
int res = pstat.executeUpdate();
System.out.println(res > 0 ? "插入資料成功" : "插入資料失敗");
} catch (Exception e) {
e.printStackTrace();
}
}
// 查詢方法 查詢全部資料
public void queryData() {
try {
String seek = "SELECT * FROM Product";
pstat = con.prepareStatement(seek);
rs = pstat.executeQuery();// 傳送查詢
while (rs.next()) {
System.out.println("產品編號" + rs.getString(1) + "\n" + "產品名稱"
+ rs.getString(2) + "\n" + "產品簡介" + rs.getString(3)
+ "\n" + "產品單價" + rs.getString(4) + "\n" + "產品數量"
+ rs.getString(5));
System.out.println("");
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new SqlDemo();
}
}