標籤:
JDBC 模版
try {
class.forName( JDBC 驅動類);
1、載入JDBC 驅動
Class. forName("com.mysql.jdbc.Driver");
2、與資料庫建立串連
connection con=DriverManager.getConnection(URL,資料庫使用者名稱,密碼);
//URL 用來標識資料庫
PreparedStatement pstmt=con.PreparedStatement("查詢sql語句");
ResultSet rs=pstmt.executeQuery();
//執行SQL語句,並得到返回結果
while (rs.next()){
int x=rs.getint("a");
String s=rs.getString("b");
float f=rs.getFloat("c");
// 處理放回結果
}
rs.close();
pstmt.close();
con.close(); //關閉串連
//釋放資源
}
package com.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;
public class Test1 {
/**
* @param args
*/
public static void main(String[] args) {
Connection conn=null;
PreparedStatement pstmt=null;
ResultSet rst=null;
try {
//1、載入驅動
Class.forName("com.mysql.jdbc.Driver");
//2、建立串連
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/nyschool?CharacterEncoding=UTF-8","root","root");
//System.out.println("建立串連成功!!");
//3、建立 prepareStatement 介面並編譯 sql語句
//pstmt=conn.prepareStatement("select * from student");
//執行刪除
Scanner input=new Scanner(System.in);
//System.out.print("請輸入要刪除的學生學號:");
//int stuNo=input.nextInt();
//兩種方法:
//方法1:String sql="DELETE FROM student WHERE stuNo="+stuNo;
//方法2:String sql="DELETE FROM student WHERE stuNo=7";
//執行添加
System.out.print("請輸入添加的學員的編號:");
int stuNo=input.nextInt();
System.out.print("請輸入添加學員的性別:");
String name=input.next();
System.out.print("請輸入添加的地址:");
String phone=input.next();
//
String sql="INSERT INTO student VALUES (?,‘a2323‘,‘qq‘,?,1,?,‘江西南昌‘,SYSDATE(),‘qq.com‘)";
pstmt=conn.prepareStatement(sql); //先行編譯方式
//給預留位置賦值
pstmt.setInt(1, stuNo);
pstmt.setString(2, name);
pstmt.setString(3, phone);
System.out.print("sql:"+sql);
//4、執行SQL語句,並得到返回結果
//rst=pstmt.executeQuery(); //執行查詢
int num=pstmt.executeUpdate(); //執行增刪改
//5、處理返回結果
if(num>0){
System.out.println("\n添加成功!");
}else{
System.out.println("\n添加失敗!");
}
while (rs.next()){
int x=rs.getint("a");
String s=rs.getString("b");
float f=rs.getFloat("c");
// 處理放回結果
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Java 第27章 JDBC