#JDBC 单元作业
#解答:
##MySQL建立表格CREATE TABLE `product` (`Id` int NOT NULL AUTO_INCREMENT ,`ProductName` varchar(100) NULL ,`Inventory` int NULL ,PRIMARY KEY (`Id`));
##初始化表格数据
INSERT INTO `product` (`Id`, `ProductName`, `Inventory`) VALUES ('1', 'bread', '11');INSERT INTO `product` (`Id`, `ProductName`, `Inventory`) VALUES ('2', 'milk', '8');
##读取商品ID为1的商品记录,输出商品名称和库存数量
package com.hava.jdbc;import java.sql.*;/** * Created by yanfa on 2016/9/22. */public class ProductJDBC { static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://192.168.1.200/test"; static final String USER = "root"; static final String PASSWORD = "dVHJtG0T:pf*"; public static void findFirstOne() throws ClassNotFoundException { Connection connection = null; Statement statement = null; ResultSet resultSet = null; // 1. add Driver Class.forName(JDBC_DRIVER); // 2. create db connnection try { connection = DriverManager.getConnection(DB_URL,USER,PASSWORD); // 3.run SQL statement = connection.createStatement(); resultSet = statement.executeQuery("SELECT * FROM `product` WHERE `Id` = '1' LIMIT 0, 1000"); // 4.get userName while(resultSet.next()) { Integer index = resultSet.getRow(); Integer Id = resultSet.getInt("Id"); String ProductName = resultSet.getString("ProductName"); Integer Inventory = resultSet.getInt("Inventory"); System.out.println("resultSet [row]:" + index + " [product.Id]:" + Id + " [product.ProductName]:" + ProductName + " [product.Inventory]:" + Inventory); } } catch (SQLException e) { // Exception e.printStackTrace(); } finally { try { // 5. close connection if(connection != null) connection.close(); if(statement != null) statement.close(); if(resultSet != null) resultSet.close(); } catch (SQLException e) { e.printStackTrace(); } } }}
##测试类
package com.hava.jdbc;import junit.framework.TestCase;/** * Created by zhanpeng on 2016/9/22. */public class ProductJDBCTest extends TestCase { public void testFindFirstOne() throws Exception { System.out.println("Class ProductJDBCTest Method testFindFirstOne"); ProductJDBC.findFirstOne(); }}
##打印输出
Class ProductJDBCTest Method testFindFirstOneresultSet [row]:1 [product.Id]:1 [product.ProductName]:bread [product.Inventory]:11Process finished with exit code 0