標籤:資料 price 執行sql lips statement base 取數 好的 添加
Java Database Connector Step :
(Eclipse)
在工程項上右擊,點擊最下面的Properties ,然後按照以下關鍵字順序操作,即可將匯入jar包。
關鍵點:1.Java Build Path
2.Libraries
3.Add External JARs(添加本地jars包)
4.Apply
JDBC常用介面、類 :
1.資料庫驅動
Driver介面和DriverManager類
2.資料庫連接
Connection類
3.執行sql文
Statement類
PreparedStatement類(可以包含預留位置)
代碼參考:
package com.zczr.ja01;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.sql.Connection;public class JDBC_Test01 { public static void main(String[] args) { Connection con = null; Statement stat = null; ResultSet rs = null ; // JDBC - java database connector try { // 載入mysql的驅動,並且將mysql的驅動載入到DriverManage類中 Class.forName("com.mysql.jdbc.Driver"); // 串連地址 String url = "jdbc:mysql://127.0.0.1:3306/goods"; //使用者名稱 String userName = "root"; //使用者密碼 String password = "1234"; // 通過驅動管理員擷取資料庫的連線物件(Connection),要通過的資料庫連結地址、資料庫使用者名稱、密碼 con = DriverManager.getConnection(url,userName,password); //編寫SQL 陳述式 String sql = "select * from goodsinfo"; //擷取sql的執行對象 stat = con.createStatement(); /** * 使用sql執行對象來執行已經編寫好的sql語句 * 並且返回一個執行結果集(ResultSet) */ rs = stat.executeQuery(sql); while(rs.next()) { int id = rs.getInt("gid"); String name = rs.getString("gname"); String type = rs.getString("gtype"); double price = rs.getDouble("price"); int num = rs.getInt("num"); int order = rs.getInt("oder"); String sr = id + " " + name + " " + " " + price + " " + num + " " + order + "\n"; System.out.println("查詢結果為:\n" + sr); } } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ try { if(rs != null) { rs.close(); } if(stat != null) { rs.close(); } if(con != null) { rs.close(); } }catch(SQLException e) { e.printStackTrace(); } } } }
MySQL--- JDBC