//
本地数据库已有的数据,要从这个表中过滤出Id为1的行,然后把该ProductName和Inventory输出
1 import java.sql.Connection;
2 import java.sql.DriverManager;
3 import java.sql.ResultSet;
4 import java.sql.SQLException;
5 import java.sql.Statement;
6
7
8 /**
9 * @author 神余健芝
10 * @date 创建时间:2017年5月18日 下午6:11:07
11 */
12 public class MySQLDemo {
13
14 static final String DRIVER_NAME = "com.mysql.jdbc.Driver";
15 static final String DB_URL = "jdbc:mysql://localhost/shen_db?useUnicode=true&characterEncoding=utf-8&useSSL=false";
16 static final String DB_USER_NAME = "root";
17 static final String DB_PASSWORD = "123456";
18
19 public static void main(String[] args) throws ClassNotFoundException {
20 helloworld();
21 }
22
23 public static void helloworld() throws ClassNotFoundException {
24 Connection connection = null;
25 Statement statement = null;
26 ResultSet resultSet = null;
27
28 // 1、装载驱动程序
29 Class.forName(DRIVER_NAME);
30 // 2、建立数据库链接
31 try {
32 connection = DriverManager.getConnection(DB_URL, DB_USER_NAME,DB_PASSWORD);
33 // 3、执行SQL语句
34 statement = connection.createStatement();
35 resultSet = statement.executeQuery("select * from test where Id=1");
36 // 4、获取结果
37 while (resultSet.next()) {
38 System.out.println("ProductName:" + resultSet.getString("ProductName"));
39 System.out.println("Inventory:"+resultSet.getString("Inventory"));
40 }
41 } catch (SQLException e) {
42 // 异常处理
43 e.printStackTrace();
44 } finally {
45 //清理资源
46 try {
47 if (connection != null) {
48 connection.close();
49 }
50 if (statement != null) {
51 statement.close();
52 }
53 if (resultSet != null) {
54 resultSet.close();
55 }
56 } catch (SQLException e) {
57 // 忽略
58 }
59 }
60 }
61 }