码迷,mamicode.com
首页 > 数据库 > 详细

JDBC学习笔记(2):创建数据库连接

时间:2015-03-15 19:40:00      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:

1.建立数据库

 

 1     --创建数据库
 2     create database jdbc;
 3     --调用数据库
 4     use jdbc;
 5     --创建user表
 6     create table user
 7     (
 8     id integer not null auto_increment,
 9     name varchar(45) not null,
10     birthday date not null,
11     money float not null,
12     primary key(id)
13     );
14     --插入数据
15     insert into user(name,birthday,money) values(zhangs,1985-01-01,100);
16     insert into user(name,birthday,money) values(lisi,1986-01-01,200);
17     insert into user(name,birthday,money) values(wangwu,1987-01-01,300); 

 

 

2.JDBC操作的基本步骤

  (1)加载驱动:只需加载一次

   (2)建立连接:建立与数据库的连接,DriverManager.getConnection(url,username,password); url格式:jdbc:协议名称:子名 称//主机地址:端口号/数据库名称  username:数据库用户名  password:密码

  (3)创建语句

  (4)执行语句

  (5)处理执行结果

  (6)关闭连接,释放资源

 demo:

 1 package com.xxyh.jdbc;
 2 import java.sql.Connection;
 3 import java.sql.DriverManager;
 4 import java.sql.ResultSet;
 5 import java.sql.SQLException;
 6 import java.sql.Statement;
 7 public class Base {
 8     public static void main(String[] args) throws ClassNotFoundException, SQLException {
 9         
10         String url = "jdbc:mysql://localhost:3306/jdbc";
11         String user = "root";
12         String password = "1234";
13         
14         Connection conn = null;
15         Statement stmt = null;
16         ResultSet rs = null;
17         try {
18             // 注册驱动
19             Class.forName("com.mysql.jdbc.Driver");
20             
21             // 建立连接
22             conn = DriverManager.getConnection(url, user, password);
23             
24             // 创建语句
25             stmt = conn.createStatement();
26             
27             // 执行语句
28             rs = stmt.executeQuery("select * from user");
29             
30             // 处理结果集
31             while(rs.next()) {
32                 System.out.println(rs.getObject("id") + "\t" + rs.getObject("name") + "\t" +
33                         rs.getObject("birthday") + "\t" + rs.getObject("money"));
34             }
35         } finally {
36             try {
37                 if (rs != null) {
38                     rs.close();
39                 }
40             } finally {
41                 try {
42                     if (stmt != null) {
43                         stmt.close();
44                     }
45                 } finally {
46                     if (conn != null) {
47                         conn.close();
48                     }
49                 }
50             }
51         }
52         
53     }
54 }
【运行结果】:
1    zhangs    1985-01-01    100.0
2    lisi      1986-01-01    200.0

3    wangwu    1987-01-01    300.0  

JDBC学习笔记(2):创建数据库连接

标签:

原文地址:http://www.cnblogs.com/xiaoxiaoyihan/p/4340183.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!