close

※由使用者輸入資料存入資料庫

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.Scanner;

public class Test0617 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String[] Data = new String[3];
        String str = scanner.next();
        String[] dataArray = str.split(",");
        int i = 0;
        for(String data : dataArray){
            Data[i] = data;
            i++;
        }
        try {
            Connection con = DriverManager.getConnection("jdbc:derby://localhost/Test", "user1", "pass");
            Statement stamt  = con.createStatement();
            String sql = String.format("insert into cu values(%d,'%s','%s')",Integer.valueOf(Data[0]),Data[1],Data[2]);
            stamt.executeUpdate(sql);
        } catch (Exception e) {
            e.printStackTrace();
        }           
    }
}

Input:
4,test,test


※查詢資料庫中的資料表內容

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class Test0617 {
    public static void main(String[] args) {
        try {
            Connection con = DriverManager.getConnection("jdbc:derby://localhost/Test", "user1", "pass");
            Statement stamt  = con.createStatement();
            ResultSet rs = stamt.executeQuery("select * from cu");
            while(rs.next()){
                System.out.printf("customer_id = %3s\t",String.valueOf(rs.getObject("cid")));
                System.out.printf("name = %3s\t",String.valueOf(rs.getObject("cname")));
                System.out.printf("address = %3s\t",String.valueOf(rs.getObject("address")));
                System.out.println("");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }           
    }
}

Out:

customer_id =   1    name = ABC    address = DEF    
customer_id =   2    name =   1    address =   1    
customer_id =   3    name =   1    address =   1    
customer_id =   4    name = test    address = test    

 

arrow
arrow
    文章標籤
    java Databases
    全站熱搜
    創作者介紹
    創作者 淺翔 的頭像
    淺翔

    翔の學習淺談

    淺翔 發表在 痞客邦 留言(0) 人氣()