1. 程式人生 > >JDBC及常見數據存取問題

JDBC及常見數據存取問題

關閉連接 顯示 not auth ces url row oca insert

連接數據庫步驟:

註冊驅動:Class.forName("com.mysql.jdbc.Driver");

設置數據庫地址、用戶名、密碼:String url = "jdbc:mysql://localhost:3306/database";

創建連接:Connection conn = DriverManager.getConnection(url, username, password);

創建sql語句字符串:String sql = "insert into tb_books(name,price,bookCount,author) values(?,?,?,?)";

使用PreparedStatement處理sql語句:PreparedStatement ps = conn.prepareStatement(sql);

設置缺省數據:ps.setString(1, variable);

執行sql語句,返回受影響行數:int row = ps.executeUpdate();

釋放對象:ps.close();

關閉連接:conn.close();

    out.println(request.getParameter("price"));
    double price = Double.parseDouble(request.getParameter("price"));
    out.println(price);
    try {
        Class.forName("com.mysql.jdbc.Driver
"); String url = "jdbc:mysql://localhost:3306/test"; String username = "root"; String password = "123456"; Connection conn = DriverManager.getConnection(url, username, password); String sql = "insert into tb_books(name,price,bookCount,author) values(?,?,?,?)"; PreparedStatement ps
= conn.prepareStatement(sql); ps.setString(1, book.getName()); ps.setDouble(2, price); ps.setInt(3, book.getBookCount()); ps.setString(4, book.getAuthor()); int row = ps.executeUpdate(); if (row > 0) { out.print("成功添加了" + row + "條數據!"); } ps.close(); conn.close(); } catch (Exception e) { out.print("添加失敗!"); e.printStackTrace(); }

    try {
        Class.forName("com.mysql.jdbc.Driver");
        String url = "jdbc:mysql://localhost:3306/test";
        String username = "root";
        String password = "123456";
        Connection conn = DriverManager.getConnection(url, username, password);
        if (conn != null) {
            out.println("success!!");
            conn.close();
        } else {
            out.println("fail");
        }
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (SQLException e) {
        e.printStackTrace();
    }


Q:輸入的是小數,但是存入之後顯示的是四舍五入後的整數。

A:float最多表示7位有效數據。double最多表示16位有效數據。改了double類型的位數為0,就好了。


JDBC及常見數據存取問題