JDBC及常見資料存取問題

來源:互聯網
上載者:User

標籤:資料   oat   表示   nec   com   parameter   設定   輸入   getc   

 串連資料庫步驟:

註冊驅動: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及常見資料存取問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.