標籤:資料 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及常見資料存取問題