Java JDBC連接數據庫實例

問題描述:向數據庫按照一定規則增加記錄,顯示一條一條記錄向數據庫中增加不是好的方式,應該由程序去實現。
現在給出實例:
JdbcUtils工具類:

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

/**
 * 
 * JDBC工具類,回去數據庫連接和釋放連接
 */
public class JdbcUtils {
    private static String driver = null;
    private static String url = null;
    private static String username = null;
    private static String password = null;
    // 加載驅動,獲取數據庫連接信息
    static {
        try {
            // 加載配置文件
            InputStream in = JdbcUtils.class.getClassLoader()
                    .getResourceAsStream("DB.properties");
            Properties properties = new Properties();
            properties.load(in);
            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");
            // 加載驅動
            Class.forName(driver);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * 
     * 獲取數據庫連接
     * 
     * @throws SQLException
     */
    public static Connection getConnection() {
        try {
            return DriverManager.getConnection(url, username, password);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 釋放資源
     * 
     * @param connection
     * @param preparedStatement
     * @param resultSet
     */
    public static void releaseDB(Connection connection,
            PreparedStatement preparedStatement, ResultSet resultSet) {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if (preparedStatement != null) {
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

}

DB.properties 配置文件

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://目標URL/數據庫
username=#your 用戶名
password=# your 密碼

JdbcTest CRUD 操作

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JdbcTest {

    /*
     * 增加
     */
    public void create() {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {
            // 獲取連接
            connection = JdbcUtils.getConnection();

            String carnumber_head = "甬-K-1F-";
            for (int i = 1; i <= 100; i++) {

                if (i < 10) {
//                  System.out.println("value------>>>" + carnumber_head+"000" + i);
                     // 準備sql語句
                    String sql = "INSERT INTO cx_carnumberpool(carnumber) VALUES(?)";
                    // 獲取PrepareStatement對象
                    preparedStatement = connection.prepareStatement(sql);
                    // 填充佔位符
                    preparedStatement.setString(1, carnumber_head+"000" + i);
                    int num = preparedStatement.executeUpdate();// 返回影響到的行數

                    System.out.println("一共影響到" + num + "行");

                } else if (i < 100) {
                     // 準備sql語句
                    String sql = "INSERT INTO cx_carnumberpool(carnumber) VALUES(?)";
                    // 獲取PrepareStatement對象
                    preparedStatement = connection.prepareStatement(sql);
                    // 填充佔位符
                    preparedStatement.setString(1, carnumber_head+"00" + i);
                    int num = preparedStatement.executeUpdate();// 返回影響到的行數

                    System.out.println("一共影響到" + num + "行");
                } else if (i < 1000) {
                     // 準備sql語句
                    String sql = "INSERT INTO cx_carnumberpool(carnumber) VALUES(?)";
                    // 獲取PrepareStatement對象
                    preparedStatement = connection.prepareStatement(sql);
                    // 填充佔位符
                    preparedStatement.setString(1, carnumber_head+"0" + i);
                    int num = preparedStatement.executeUpdate();// 返回影響到的行數
                    System.out.println("一共影響到" + num + "行");
                } 

            }




        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            JdbcUtils.releaseDB(connection, preparedStatement, null);
        }
    }

    /*
     * 讀取查詢
     */
    public void retrieve() {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            connection = JdbcUtils.getConnection();
            String sql = "SELECT user_name,user_password,user_birth FROM user";
            preparedStatement = connection.prepareStatement(sql);
            resultSet = preparedStatement.executeQuery();

            // 遍歷結果集
            while (resultSet.next()) {
                String username = resultSet.getString(1);
                String password = resultSet.getString(2);
                Date userbirth = resultSet.getDate(3);

                System.out.println(username + ":" + password + ":" + userbirth);
            }
        } catch (Exception e) {
            // TODO: handle exception
        } finally {
            JdbcUtils.releaseDB(connection, preparedStatement, resultSet);
        }

    }

    /*
     * 修改更新
     */
    public void update() {

        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {
            connection = JdbcUtils.getConnection();
            String sql = "UPDATE USER SET user_password = ? WHERE user_name = ?";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, "passwordupdate");
            preparedStatement.setString(2, "mary");
            int num = preparedStatement.executeUpdate();

            System.out.println("一共影響到" + num + "行");
        } catch (Exception e) {
            // TODO: handle exception
        } finally {
            JdbcUtils.releaseDB(connection, preparedStatement, null);
        }
    }

    /*
     * 刪除
     */
    public void delete() {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {
            connection = JdbcUtils.getConnection();
            String sql = "DELETE FROM user WHERE user_id = ?";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1, 3);
            int num = preparedStatement.executeUpdate();

            System.out.println("一共影響到" + num + "行");
        } catch (Exception e) {
            // TODO: handle exception
        } finally {
            JdbcUtils.releaseDB(connection, preparedStatement, null);
        }

    }

    public static void main(String[] args) {

         JdbcTest test = new JdbcTest();
         test.create();

    }

}

實例會上傳至CSDN 資源中

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