JDBC 連接mysql數據庫

package db;


import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;


public class JDBCUtil {


// 驅動包名和數據庫url
    private static String url = null;
    private static String driverClass = null;
    // 數據庫用戶名和密碼
    private static String userName = null;
    private static String password = null;
    
    /**
     * 初始化驅動程序
     * 靜態代碼塊中(只加載一次)
     */
    static{
        try {
            //讀取db.properties文件
            Properties prop = new Properties();


            /**
             * 使用類路徑的讀取方式
             *  / : 斜槓表示classpath的根目錄
             *     在java項目下,classpath的根目錄從bin目錄開始
             *     在web項目下,classpath的根目錄從WEB-INF/classes目錄開始
             */
            InputStream in = JDBCUtil.class.getResourceAsStream("/db.properties");


            //加載文件
            prop.load(in);
            //讀取信息
            url = prop.getProperty("url");
            driverClass = prop.getProperty("driverClass");
            userName = prop.getProperty("user");
            password = prop.getProperty("password");


            //註冊驅動程序
            Class.forName(driverClass);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("驅程程序註冊出錯");
        }
    }


    /**
     * 打開數據庫驅動連接
     */
    public static Connection getConnection(){
        try {
            Connection conn = DriverManager.getConnection(url, userName, password);
            return conn;
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }






    /**
     * 清理環境,關閉連接(順序:後打開的先關閉)
     */
    public static void close(Connection conn,Statement stmt,ResultSet rs){
        if(rs!=null)
            try {
                rs.close();
            } catch (SQLException e1) {
                e1.printStackTrace();
                throw new RuntimeException(e1);
            }
        if(stmt!=null){
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
        }
    }


    public static void main(String[] args) {


        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;




        conn=JDBCUtil.getConnection();
        try {
             stmt=conn.createStatement();
             //準備sql操作語句
             String sql= "SELECT cid,name,address FROM client";
             rs = stmt.executeQuery(sql);


             //從結果集中提取數據
             while(rs.next()){
                  int cid  = rs.getInt("cid");
                  String name = rs.getString("name");
                  String address = rs.getString("address");
                 


                  System.out.print("CID: " + cid);
                  System.out.print(", name: " + name);
                  System.out.println(", address: " + address);
             }
           } catch (SQLException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
           }finally{
               JDBCUtil.close(conn, stmt, rs);
           }
      }

}


// db.properties文件

url=jdbc:mysql://localhost/fdb
user=root
password=root
driverClass=com.mysql.jdbc.Driver


package db;


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;


import entity.Client;


public class ClientDao {
private Connection conn = JDBCUtil.getConnection();
    
    private ResultSet rs = null;




/**
* 添加一個Client
* @param c
* @return
*/
public int addClient(Client c){
String sql= "insert into  client(name,address) values(?,?)";
int i = 0;
try{
PreparedStatement ptmt=conn.prepareStatement(sql);
ptmt.setString(1, c.getName());
ptmt.setString(2, c.getAddress());
i = ptmt.executeUpdate();
ptmt.close();
conn.close();
}catch(SQLException  e){
e.printStackTrace();
}
return i;
}

/**
* 更新Client的Name字段
* @param c
* @return
*/
public int updateClientName(Client c){
String sql = "update  client set name='"+c.getName()+"' where cid="+c.getCid();
int i=0;
try{
PreparedStatement  pstmt = (PreparedStatement) conn.prepareStatement(sql);
    i = pstmt.executeUpdate();
    pstmt.close();
    conn.close();
}catch (SQLException e) {
        e.printStackTrace();
    }
return i;
}
/**

* @param c
* @return
*/
public int updateClientAddress(Client c){
String sql = "update  client set address='"+c.getAddress()+"' where cid="+c.getCid();
int i=0;
try{
PreparedStatement  pstmt = (PreparedStatement) conn.prepareStatement(sql);
    i = pstmt.executeUpdate();
    pstmt.close();
    conn.close();
}catch (SQLException e) {
        e.printStackTrace();
    }
return i;
}


/**
* 根據cid刪除Client
* @param c
* @return
*/
public int delClientById(Client c){
String sql= "delete from   client where cid=?";
int i = 0;
try{
PreparedStatement ptmt=conn.prepareStatement(sql);
ptmt.setInt(1, c.getCid());
i = ptmt.executeUpdate();
ptmt.close();
conn.close();
}catch(SQLException  e){
e.printStackTrace();
}
return i;
}

/**
* 根據Cid查詢Client
* @param c
* @return 返回一個Client
*/
public Client selClientById(Client c){
String sql= "select cid,name,address from   client where cid=?";
Client client = new Client();
try{
PreparedStatement ptmt=conn.prepareStatement(sql);
ptmt.setInt(1, c.getCid());
ResultSet  rs =ptmt.executeQuery();
while(rs.next()){
int cid = rs.getInt(1);
String name = rs.getString(2);
String addr = rs.getString(3);
client.setCid(cid);
client.setName(name);
client.setAddress(addr);
}
ptmt.close();
conn.close();
}catch(SQLException  e){
e.printStackTrace();
}
return client;
}

/**
* 根據Address查詢Client
* @param c
* @return Client的列表
*/
public List<Client> selClientByAddress(Client c){
String sql= "select cid,name,address from   client where address=?";
List<Client> list = new ArrayList<Client>();

try{
PreparedStatement ptmt=conn.prepareStatement(sql);
ptmt.setString(1, c.getAddress());
ResultSet  rs =ptmt.executeQuery();
while(rs.next()){
int cid = rs.getInt(1);
String name = rs.getString(2);
String addr = rs.getString(3);
Client client = new Client();
client.setCid(cid);
client.setName(name);
client.setAddress(addr);
list.add(client);
}
ptmt.close();
conn.close();
}catch(SQLException  e){
e.printStackTrace();
}
return list;
}

/**
* 根據Name查詢Client
* @param c
* @return
*/
public List<Client> selClientByName(Client c){
String sql= "select cid,name,address from   client where name=?";
List<Client> list = new ArrayList<Client>();

try{
PreparedStatement ptmt=conn.prepareStatement(sql);
ptmt.setString(1, c.getName());
ResultSet  rs =ptmt.executeQuery();
while(rs.next()){
int cid = rs.getInt(1);
String name = rs.getString(2);
String addr = rs.getString(3);
Client client = new Client();
client.setCid(cid);
client.setName(name);
client.setAddress(addr);
list.add(client);
}
ptmt.close();
conn.close();
}catch(SQLException  e){
e.printStackTrace();
}
return list;
}



public static void main(String[] args) {
// TODO Auto-generated method stub


}


}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章