jdbc java数据库连接 1)jdbc入门

 

之前操作数据

  1)通过mysql的客户端工具,登录数据库服务器  (mysql -u root -p 密码)

  2)编写sql语句

  3)发送sql语句到数据库服务器执行 

什么是jdbc

   使用java代码(程序)发送sql语句的技术,就是jdbc技术!!!!

使用jdbc发送sql前提

  1. 登录数据库服务器(连接数据库服务器)
  2. 数据库的IP地址
  3. 端口
  4. 数据库用户名
  5. 密码

 

代码:

  

 1 public class MySql_Demo1 {
 2 
 3         //创建一个url
 4         private static String url = "jdbc:mysql://localhost:3306";
 5     
 6         //创建数据库信息
 7         private static String user = "root";
 8         private static String possword = "root";
 9     
10         //第一种方式
11         private static void connection1() throws SQLException {
12             
13             //创建驱动类对象
14             Driver driver = new com.mysql.jdbc.Driver();
15             
16             //用个集合接收下数据库信息
17             Properties pro = new Properties();
18             pro.getProperty("user", user);
19             pro.getProperty("possword", possword);
20             
21             //连接
22             Connection con = driver.connect(url, pro);
23 
24         }
25         
26         //第二种方式
27         /**
28          * 用驱动管理器连接
29          * @throws SQLException 
30          */
31     
32         private static void connection2() throws SQLException {
33             
34             //注册驱动程序
35             //通过源码,就知道这个方法自动注册了,所以没必要再new一个驱动对象
36             Driver driver = new com.mysql.jdbc.Driver();
37             
38             //连接到具体的数据库
39             Connection conn = DriverManager.getConnection(url, user, possword);
40                 
41         }
42         
43         //第三种方法(推荐)
44         /**
45          * 从看Driver driver = new com.mysql.jdbc.Driver();的源码
46          * 就知道,它里面的方法是个静态方法,随着类的加载而启动,所以,我们可以直接用类来调用,传递url字段过去
47          * @param args
48          * @throws Exception
49          */
50         private static void connection3() throws Exception {
51             
52             //直接传递url字段过去,加载静态代码,从而注册驱动程序
53             Class.forName("com.mysql.jdbc.Driver");
54             
55             //连接到具体的数据库
56             // DriverManager.getConnection(url, user, possword):试图建立到给定数据库 URL 的连接。
57             Connection con = DriverManager.getConnection(url, user, possword);
58             
59         }
60             
61         public static void main(String[] args) throws Exception {
62             connection3();
63         }
64             
65 }

 

posted @ 2016-10-29 22:43  卡拉瓦  阅读(290)  评论(0编辑  收藏  举报