jdbc方式链接数据库小结

1.下载mysql和Navicat for MySQL(可视化工具)

2.在eclipse下新建一个项目File->new->Dynamic Web Project同时部署好tomcat。

3.导入jar包。方法:

   右键你的项目:build path->configure Build Path

 

选择第三个:Libraries->Add External JARS,选择你的mysql jar包

然后确定

注意:此时打开它的文件结构是这样的:

 

Jar包不要导错了。否则后续会有很多麻烦。

4.建立一个数据库

 

此处请参考数据库系统概论相关知识。

 

 1 public class JDBCTest {
 2     public static Connection getConnection(){
 3         Connection conn = null;
 4         try {
 5             Class.forName("com.mysql.jdbc.Driver");
 6             String url ="jdbc:mysql://localhost/keshe?useUnicode=true&charset=utf8";
 7             conn = DriverManager.getConnection(url,"root","2013005488");
 8             System.out.println(conn.getMetaData().getURL());
 9             System.out.println("success");
10         } catch (Exception e) {
11             // TODO: handle exception
12         }
13         return conn;
14         
15     }
16 
17     public static void insert(){
18         Connection conn = getConnection();
19         try {
20             String sql = "INSERT INTO usertable (username,password)"+" values ('yang','123456')";
21             Statement stmt = null;
22             ResultSet rs = null;
23             
24             stmt = conn.createStatement();
25             int count = stmt.executeUpdate(sql);
26             System.out.println("向用户表中插入了"+count+"条记录");
27             conn.close();
28         } catch (Exception e) {
29             // TODO: handle exception
30         }
31     }
32     public static void main(String[] args) {
33 
34         getConnection();
35         insert();
36         upDate();
37         delete();
38         
39     }
40     public static void upDate(){
41         Connection conn = getConnection();
42         try {
43             String sql = "update usertable set username ='sunyawen' where user_id = 1 ";
44             Statement stmt = null;
45             ResultSet rs = null;
46             
47             stmt = conn.createStatement();
48             int count = stmt.executeUpdate(sql);
49             System.out.println("向用户表中修改了"+count+"条记录");
50             conn.close();
51         } catch (Exception e) {
52             // TODO: handle exception
53         }
54     }
55     
56     public static void delete(){
57         Connection conn = getConnection();
58         try {
59             String sql = "delete from usertable where username ='sunyawen'";
60             Statement stmt = null;
61             ResultSet rs = null;
62             
63             stmt = conn.createStatement();
64             int count = stmt.executeUpdate(sql);
65             System.out.println("向用户表中删除了"+count+"条记录");
66             conn.close();
67         } catch (Exception e) {
68             // TODO: handle exception
69         }
70     }
71 }

后来 我发现导入jar包还有更简单的方法,即直接将jar包复制粘贴到lib文件夹下,简单粗暴。

 

posted @ 2016-09-16 17:51  杨玲枝  阅读(213)  评论(0编辑  收藏  举报