当前位置:Gxlcms > 数据库问题 > JDBC

JDBC

时间:2021-07-01 10:21:17 帮助过:22人阅读

技术分享
 1 CREATE TABLE `customers` (
 2   `id` int(11) NOT NULL auto_increment,
 3   `name` varchar(30) NOT NULL,
 4   `address` varchar(30) default ‘‘,
 5   `phone` varchar(30) default ‘‘,
 6   `email` varchar(30) default ‘‘,
 7   `birth` date default NULL,
 8   PRIMARY KEY  (`id`),
 9   UNIQUE KEY `name` (`name`)
10 ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
View Code

 

001-通过Driver接口获取数据库连接

  Driver 是一个接口: 数据库厂商必须提供实现的接口. 能从其中获取数据库连接。
  可以通过 Driver的实现类对象获取数据库连接。
  1. 加入MySQL驱动
  ⑴解压"mysql-connector-java-5.1.7.zip"。
  ⑵在当前项目下新建"lib"目录。
  ⑶把"mysql-connector-java-5.1.7-bin.jar"复制到lib目录下。
  ⑷右键"Build Path"→"Add to Build Path"加入到类路径下。

技术分享
 1 package com.atguigu.jdbc;
 2 
 3 import java.sql.Connection;
 4 import java.sql.Driver;
 5 import java.sql.SQLException;
 6 import java.util.Properties;
 7 
 8 import org.junit.Test;
 9 
10 public class JDBCTest1 {
11   @Test
12   public void testDriver() throws SQLException {
13     //1. 创建一个 Driver实现类的对象
14     Driver driver = new com.mysql.jdbc.Driver();
15     //2. 准备连接数据库的基本信息: url、user、password
16     String url = "jdbc:mysql://localhost:3306/atguigu";
17     Properties info = new Properties();
18     info.put("user", "root");
19     info.put("password", "123456");
20     //3. 调用 Driver 接口的 connect(url, info) 获取数据库连接
21     Connection connection = driver.connect(url, info);
22     System.out.println(connection);
23   }    
24 }
JDBCTest1.java

  第8行,需要加入单元测试:右键“Properties”在窗口中,首先在左边选择“Java Build Path”,然后到右上选择“Libraries”标签,之后在最右边点击“Add Library…”按钮,选择“JUnit4”。
  第16行,数据库的库名:atguigu。

  编写一个通用的方法, 在不修改源程序的情况下, 可以获取任何数据库的连接
  解决方案: 把数据库驱动Driver实现类的全类名、url、user、password 放入一个配置文件(jdbc.properties)中, 通过修改配置文件的方式实现和具体的数据库解耦。

技术分享
 1 package com.atguigu.jdbc;
 2 
 3 import java.io.InputStream;
 4 import java.sql.Connection;
 5 import java.sql.Driver;
 6 import java.util.Properties;
 7 
 8 import org.junit.Test;
 9 
10 public class JDBCTest2 {
11   public Connection getConnection() throws Exception {
12     String driverClass = null;
13     String jdbcUrl = null;
14     String user = null;
15     String password = null;
16     //读取类路径下的jdbc.properties文件(在src下)
17     InputStream in = getClass().getClassLoader().getResourceAsStream("jdbc.properties");
18     Properties properties = new Properties();
19     properties.load(in);
20     driverClass = properties.getProperty("driver");
21     jdbcUrl = properties.getProperty("jdbcUrl");
22     user = properties.getProperty("user");
23     password = properties.getProperty("password");
24     //通过反射常见Driver对象 
25     Driver driver = (Driver) Class.forName(driverClass).newInstance();
26     Properties info = new Properties();
27     info.put("user", user);
28     info.put("password", password);
29     //通过Driver的connect方法获取数据库连接.
30     Connection connection = driver.connect(jdbcUrl, info);
31     return connection;
32   }
33   @Test
34   public void testGetConnection() throws Exception{
35     System.out.println(getConnection());
36   }
37 }
JDBCTest2.java

  DriverManager是驱动的管理类
  ⑴可以通过重载的 getConnection()方法获取数据库连接. 较为方便。
  ⑵可以同时管理多个驱动程序: 若注册了多个数据库连接, 则调用 getConnection()方法时传入的参数不同, 即:返回不同的数据库连接。

技术分享
 1 package com.atguigu.jdbc;
 2 
 3 import java.sql.Connection;
 4 import java.sql.DriverManager;
 5 
 6 import org.junit.Test;
 7 
 8 public class JDBCTest3 {
 9   @Test
10   public void testDriverManager() throws Exception {
11     //1. 准备连接数据库的4个字符串. 
12     String driverClass = "com.mysql.jdbc.Driver"; //驱动的全类名 
13     String jdbcUrl = "jdbc:mysql:///atguigu"; //JDBC URL   
14     String user = "root"; //user 
15     String password = "123456"; //password
16 
17     //2. 加载数据库驱动程序(对应的 Driver 实现类中有注册驱动的静态代码块.)
18     Class.forName(driverClass);
19 
20     //3. 通过 DriverManager 的 getConnection() 方法获取数据库连接. 
21     Connection connection =  DriverManager.getConnection(jdbcUrl, user, password);
22     System.out.println(connection); 
23   }
24 }
JDBCTest3.java

 

技术分享
 1 package com.atguigu.jdbc;
 2 
 3 import java.io.InputStream;
 4 import java.sql.Connection;
 5 import java.sql.DriverManager;
 6 import java.util.Properties;
 7 
 8 import org.junit.Test;
 9 
10 public class JDBCTest4 {
11   public Connection getConnection2() throws Exception{
12     //1. 准备连接数据库的4个字符串. 
13     //⑴创建Properties对象
14     Properties properties = new Properties();
15     //⑵ 获取jdbc.properties对应的输入流
16     InputStream in = this.getClass().getClassLoader().getResourceAsStream("jdbc.properties");
17     //⑶加载⑵对应的输入流
18     properties.load(in);
19     //⑷具体决定user、password 等4个字符串. 
20     String user = properties.getProperty("user");
21     String password = properties.getProperty("password");
22     String jdbcUrl = properties.getProperty("jdbcUrl");
23     String driver = properties.getProperty("driver");
24     //2. 加载数据库驱动程序(对应的Driver实现类中有注册驱动的静态代码块)
25     Class.forName(driver);
26     //3. 通过DriverManager的getConnection()方法获取数据库连接. 
27     return DriverManager.getConnection(jdbcUrl, user, password);
28   }
29   @Test
30   public void testGetConnection2() throws Exception{
31     System.out.println(getConnection2()); 
32   }
33 }
JDBCTest4.java

  通过JDB 向指定的数据表中插入一条记录.
  1. Statement: 用于执行SQ 语句的对象
  ⑴通过Connectio的createStatement()方法来获取。
  ⑵通过executeUpdate(sql)可以执行SQL语句。
  ⑶传入的SQL可以是INSRET、UPDATE或DELETE。但不能是SELECT。
  2. Connection、Statement都是应用程序和数据库服务器的连接资源. 使用后一定要关闭。需要在finally中关闭Connection和Statement对象。
  3. 关闭的顺序是: 先关闭后获取的, 即:先关闭Statement后关闭Connection。

技术分享
 1 package com.atguigu.jdbc;
 2 
 3 import java.io.InputStream;
 4 import java.sql.Connection;
 5 import java.sql.DriverManager;
 6 import java.sql.Statement;
 7 import java.util.Properties;
 8 import org.junit.Test;
 9 
10 public class JDBCTest5 {
11   @Test
12   public void testStatement() throws Exception{
13     //1. 获取数据库连接
14     Connection conn = null;
15     Statement statement = null;
16     try {
17       conn = getConnection2();
18       //3. 准备插入的SQL语句
19       String sql = null;
20       sql = "INSERT INTO customers (name, email, birth) VALUES(‘Jerry‘, ‘jerry@atguigu.com‘, ‘1991-2-12‘)";
21       // sql = "DELETE FROM customers WHERE id = 1";
22       // sql = "UPDATE customers SET name = ‘TOM‘ WHERE id = 4";
23       System.out.println(sql);
24       //4. 执行插入
25       //⑴获取操作SQL语句的Statement对象: 
26       statement = conn.createStatement();//调用Connection的createStatement()方法来获取
27       //⑵调用Statement对象的executeUpdate(sql)执行SQL语句进行插入
28       statement.executeUpdate(sql);
29     } catch (Exception e) {
30       e.printStackTrace();
31     } finally{
32       try {
33         //5. 关闭Statement对象
34         if(statement != null)
35         statement.close();
36       } catch (Exception e) {
37         // TODO Auto-generated catch block
38       e.printStackTrace();
39       } finally {
40         //2. 关闭连接
41         if(conn != null)
42         conn.close();                            
43       }
44     }
45   }
46 
47   public Connection getConnection2() throws Exception {
48     //1. 准备连接数据库的4个字符串. 
49     //⑴创建Properties对象
50     Properties properties = new Properties();    
51     //⑵获取jdbc.properties对应的输入流
52     InputStream in = this.getClass().getClassLoader().getResourceAsStream("jdbc.properties");        
53     //⑶加载⑵对应的输入流
54     properties.load(in);        
55     //⑷具体决定 user、password等4个字符串. 
56     String user = properties.getProperty("user");
57     String password = properties.getProperty("password");
58     String jdbcUrl = properties.getProperty("jdbcUrl");
59     String driver = properties.getProperty("driver");        
60     //2. 加载数据库驱动程序(对应的Driver实现类中有注册驱动的静态代码块)
61     Class.forName(driver);        
62     //3. 通过DriverManager的getConnection() 方法获取数据库连接.
63     return DriverManager.getConnection(jdbcUrl, user, password);
64   }
65 
66   @Test
67   public void testGetConnection2() throws Exception{
68     System.out.println(getConnection2()); 
69   }
70 }
JDBCTest5.java

   版本1:通用的更新的方法(包括 INSERT、UPDATE、DELETE)版本1

******************************
ORACLE
******************************
【Tue Oct 11 2016 09:37:50 GMT+0800】
使用Oracle的plsqldev.exe之前需要启动这两个服务:OracleServiceORCL和OracleOraDb10g_home1TNSListener,在Widows命令行
net start oracleserviceorclnet start OracleOraDb10g_home1TNSListener(lsnrctl start)

C:\Users\admin>net start oracleserviceorcl
OracleServiceORCL 服务正在启动 ......
OracleServiceORCL 服务已经启动成功。

C:\Users\admin>net start OracleOraDb10g_home1TNSListener
OracleOraDb10g_home1TNSListener 服务正在启动 .
OracleOraDb10g_home1TNSListener 服务已经启动成功。

 

【Sat Oct 22 2016 21:56:08 GMT+0800】

技术分享
  1 -- phpMyAdmin SQL Dump
  2 -- version 3.5.3
  3 -- http://www.phpmyadmin.net
  4 --
  5 -- 主机: localhost
  6 -- 生成日期: 2016 年 10 月 22 日 21:19
  7 -- 服务器版本: 5.5.20
  8 -- PHP 版本: 5.3.5
  9 
 10 SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
 11 SET time_zone = "+00:00";
 12 
 13 
 14 /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
 15 /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
 16 /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
 17 /*!40101 SET NAMES utf8 */;
 18 
 19 --
 20 -- 数据库: `ecshop`
 21 --
 22 
 23 -- --------------------------------------------------------
 24 
 25 --
 26 -- 表的结构 `goods`
 27 --
 28 
 29 CREATE TABLE IF NOT EXISTS `ec_goods` (
 30   `goods_id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
 31   `cat_id` smallint(5) unsigned NOT NULL DEFAULT 0,
 32   `goods_sn` varchar(60) NOT NULL DEFAULT ‘‘,
 33   `goods_name` varchar(120) NOT NULL DEFAULT ‘‘,
 34   `goods_name_style` varchar(60) NOT NULL DEFAULT +,
 35   `click_count` int(10) unsigned NOT NULL DEFAULT 0,
 36   `brand_id` smallint(5) unsigned NOT NULL DEFAULT 0,
 37   `provider_name` varchar(100) NOT NULL DEFAULT ‘‘,
 38   `goods_number` smallint(5) unsigned NOT NULL DEFAULT 0,
 39   `goods_weight` decimal(10,3) unsigned NOT NULL DEFAULT 0.000,
 40   `market_price` decimal(10,2) unsigned NOT NULL DEFAULT 0.00,
 41   `shop_price` decimal(10,2) unsigned NOT NULL DEFAULT 0.00,
 42   `promote_price` decimal(10,2) unsigned NOT NULL DEFAULT 0.00,
 43   `promote_start_date` int(11) unsigned NOT NULL DEFAULT 0,
 44   `promote_end_date` int(11) unsigned NOT NULL DEFAULT 0,
 45   `warn_number` tinyint(3) unsigned NOT NULL DEFAULT 1,
 46   `keywords` varchar(255) NOT NULL DEFAULT ‘‘,
 47   `goods_brief` varchar(255) NOT NULL DEFAULT ‘‘,
 48   `goods_desc` text NOT NULL,
 49   `goods_thumb` varchar(255) NOT NULL DEFAULT ‘‘,
 50   `goods_img` varchar(255) NOT NULL DEFAULT ‘‘,
 51   `original_img` varchar(255) NOT NULL DEFAULT ‘‘,
 52   `is_real` tinyint(3) unsigned NOT NULL DEFAULT 1,
 53   `extension_code` varchar(30) NOT NULL DEFAULT ‘‘,
 54   `is_on_sale` tinyint(1) unsigned NOT NULL DEFAULT 1,
 55   `is_alone_sale` tinyint(1) unsigned NOT NULL DEFAULT 1,
 56   `is_shipping` tinyint(1) unsigned NOT NULL DEFAULT 0,
 57   `integral` int(10) unsigned NOT NULL DEFAULT 0,
 58   `add_time` int(10) unsigned NOT NULL DEFAULT 0,
 59   `sort_order` smallint(4) unsigned NOT NULL DEFAULT 100,
 60   `is_delete` tinyint(1) unsigned NOT NULL DEFAULT 0,
 61   `is_best` tinyint(1) unsigned NOT NULL DEFAULT 0,
 62   `is_new` tinyint(1) unsigned NOT NULL DEFAULT 0,
 63   `is_hot` tinyint(1) unsigned NOT NULL DEFAULT 0,
 64   `is_promote` tinyint(1) unsigned NOT NULL DEFAULT 0,
 65   `bonus_type_id` tinyint(3) unsigned NOT NULL DEFAULT 0,
 66   `last_update` int(10) unsigned NOT NULL DEFAULT 0,
 67   `goods_type` smallint(5) unsigned NOT NULL DEFAULT 0,
 68   `seller_note` varchar(255) NOT NULL DEFAULT ‘‘,
 69   `give_integral` int(11) NOT NULL DEFAULT -1,
 70   `rank_integral` int(11) NOT NULL DEFAULT -1,
 71   `suppliers_id` smallint(5) unsigned DEFAULT NULL,
 72   `is_check` tinyint(1) unsigned DEFAULT NULL,
 73   PRIMARY KEY (`goods_id`),
 74   KEY `goods_sn` (`goods_sn`),
 75   KEY `cat_id` (`cat_id`),
 76   KEY `last_update` (`last_update`),
 77   KEY `brand_id` (`brand_id`),
 78   KEY `goods_weight` (`goods_weight`),
 79   KEY `promote_end_date` (`promote_end_date`),
 80   KEY `promote_start_date` (`promote_start_date`),
 81   KEY `goods_number` (`goods_number`),
 82   KEY `sort_order` (`sort_order`)
 83 ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=33 ;
 84 
 85 --
 86 -- 转存表中的数据 `goods`
 87 --
 88 
 89 INSERT INTO `ec_goods` (`goods_id`, `cat_id`, `goods_sn`, `goods_name`, `goods_name_style`, `click_count`, `brand_id`, `provider_name`, `goods_number`, `goods_weight`, `market_price`, `shop_price`, `promote_price`, `promote_start_date`, `promote_end_date`, `warn_number`, `keywords`, `goods_brief`, `goods_desc`, `goods_thumb`, `goods_img`, `original_img`, `is_real`, `extension_code`, `is_on_sale`, `is_alone_sale`, `is_shipping`, `integral`, `add_time`, `sort_order`, `is_delete`, `is_best`, `is_new`, `is_hot`, `is_promote`, `bonus_type_id`, `last_update`, `goods_type`, `seller_note`, `give_integral`, `rank_integral`, `suppliers_id`, `is_check`) VALUES
 90 (1, 4, ECS000000, KD876, +, 7, 8, ‘‘, 1, 0.110, 1665.60, 1388.00, 0.00, 0, 0, 1, LG 3g 876 支持 双模 2008年04月 灰色 GSM,850,900,1800,1900, ‘‘, <p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 很多朋友都已经抢先体验了3G网络的可视通话、高速上网等功能。LG KD876手机<span style="font-size: x-large;"><span style="color: rgb(255, 0, 0);"><strong>支持TD-SCDMA/GSM双模单待</strong></span></span>,便于测试初期GSM网络和TD网络之间的切换和共享。</p>\r\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; LG KD876手机整体采用银色塑料材质,<strong><span style="font-size: x-large;"><span style="color: rgb(255, 0, 0);">特殊的旋转屏设计是本机的亮点</span></span></strong>,而机身背部的300万像素摄像头也是首发的六款TD-SCDMA手机中配置最高的。LG KD876手机屏幕下方设置有外键盘,该键盘由左/右软键、通话/挂机键、返回键、五维摇杆组成,摇杆灵敏度很高,定位准确。KD876的内键盘由标准12个电话键和三个功能键、一个内置摄像头组成。三个功能键分别为视频通话、MP3、和菜单键,所有按键的手感都比较一般,键程适中,当由于按键排列过于紧密,快速发短信时很容易误按,用户在使用时一定要多加注意。LG KD876手机机身周边的接口设计非常简洁,手机的厚度主要来自屏幕旋转轴的长度,如果舍弃旋屏设计的话,估计<span style="font-size: x-large;"><strong><span style="color: rgb(255, 0, 0);">厚度可以做到10mm以下</span></strong></span>。</p>, images/200905/thumb_img/1_thumb_G_1240902890710.jpg, images/200905/goods_img/1_G_1240902890755.jpg, images/200905/source_img/1_G_1240902890895.gif, 1, ‘‘, 1, 1, 0, 
                        
                    

人气教程排行