java的jdbc操作

------- 引入gradle包

//mysql數據庫連接
compile('mysql:mysql-connector-java:8.0.15')

-------- jdbc.properties配置文件信息

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://10.1.22.15:3306/lr_order?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&useSSL=false
username=lr_order
password=6qdl7hThTgB$EQJ%

-------    獲取連接及關閉連接共有類

package com.cn.pb.util;

import java.sql.*;

/**
 * Created by lizhihao on 2019/4/4 21:22
 */
public class JdbcConnectionUtil {
    //通過工具類獲取到properties文件中的鍵值從而可以加載驅動 獲取鏈接 從而 可以增刪改查
    private static Connection conn = null;
    //獲取數據庫連接
    public static Connection getConnection(){
        String driver = PropertiesUtil.getJdbcPropertyValue("driver");
        String url = PropertiesUtil.getJdbcPropertyValue("url");
        String username  = PropertiesUtil.getJdbcPropertyValue("username");
        String password = PropertiesUtil.getJdbcPropertyValue("password");
//        System.out.printf("獲取到的數據庫連接信息:(%s,%s,%s,%s)",driver,url,username,password).println();
        try{
            Class.forName(driver).newInstance();
            conn = DriverManager.getConnection(url, username, password);
        }catch(Exception e){
            System.out.println("建立數據庫連接失敗:"+ e.getMessage());
        }
        return conn;
    }
    //關閉連接
    public static void close(){
        try{
            if(conn != null) conn.close();
        }catch(Exception e){
            System.out.println("關閉連接失敗:"+ e.getMessage());
        }
    }
}

--------------------獲取字段信息

public static void getColumnsDetail(String tableName){

//獲取數據庫連接
Connection connection = JdbcConnectionUtil.getConnection();
if(connection == null) return;
try {
    //獲取元數據信息
    DatabaseMetaData metaData = connection.getMetaData();
    //提取指定表的字段、類型、長度、註釋等信息
    ResultSet resultSet = metaData.getColumns(null, "%", tableName, "%");
    while(resultSet.next()){
     String columnName = resultSet.getString("COLUMN_NAME");//字段名
     String typeName = resultSet.getString("TYPE_NAME");//類型 數據源依賴的類型名稱,對於 UDT,該類型名稱是完全限定的
     String columnComment = resultSet.getString("REMARKS");//註釋說明
     System.out.println("columnName :"+columnName +",typeName:"+typeName +",columnComment:"+columnComment );
    }
} catch (SQLException e) {
    System.out.println("數據庫操作異常:"+e.getMessage());
}finally {
    JdbcConnectionUtil.close();
}

}

-------------------------------做增刪改查操作

-------1,創建學生類

static class Student {
        private String Id;
        private String Name;
        private String Sex;
        private String Age;

        Student(String Name, String Sex, String Age) {
            this.Id = null; //default
            this.Name = Name;
            this.Sex = Sex;
            this.Age = Age;
        }

        public String getId() {
            return Id;
        }

        public void setId(String Id) {
            this.Id = Id;
        }

        public String getName() {
            return Name;
        }

        public void setName(String Name) {
            this.Name = Name;
        }

        public String getSex() {
            return Sex;
        }

        public void setSex(String Sex) {
            this.Sex = Sex;
        }

        public String getAge() {
            return Age;
        }

        public void setage(String Age) {
            this.Age = Age;
        }
}

--------新增

private static int insert(Student student) {
    Connection conn = getConnection();
    int i = 0;
    String sql = "insert into students (Name,Sex,Age) values(?,?,?)";
    PreparedStatement pstmt;
    try {
        pstmt = (PreparedStatement) conn.prepareStatement(sql);
        pstmt.setString(1, student.getName());
        pstmt.setString(2, student.getSex());
        pstmt.setString(3, student.getAge());
        i = pstmt.executeUpdate();
        pstmt.close();
        conn.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return i;
}

------ 修改

private static int update(Student student) {
    Connection conn = getConnection();
    int i = 0;
    String sql = "update students set Age='" + student.getAge() + "' where Name='" + student.getName() + "'";
    PreparedStatement pstmt;
    try {
        pstmt = (PreparedStatement) conn.prepareStatement(sql);
        i = pstmt.executeUpdate();
        System.out.println("resutl: " + i);
        pstmt.close();
        conn.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return i;
}

----- 查詢

private static Integer getAll() {
    Connection conn = getConnection();
    String sql = "select * from students";
    PreparedStatement pstmt;
    try {
        pstmt = (PreparedStatement)conn.prepareStatement(sql);
        ResultSet rs = pstmt.executeQuery();
        int col = rs.getMetaData().getColumnCount();
        System.out.println("============================");
        while (rs.next()) {
            for (int i = 1; i <= col; i++) {
                System.out.print(rs.getString(i) + "\t");
                if ((i == 2) && (rs.getString(i).length() < 8)) {
                    System.out.print("\t");
                }
             }
            System.out.println("");
        }
            System.out.println("============================");
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return null;
}

------刪除

private static int delete(String name) {
    Connection conn = getConnection();
    int i = 0;
    String sql = "delete from students where Name='" + name + "'";
    PreparedStatement pstmt;
    try {
        pstmt = (PreparedStatement) conn.prepareStatement(sql);
        i = pstmt.executeUpdate();
        System.out.println("resutl: " + i);
        pstmt.close();
        conn.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return i;
}

 

 

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