Java JDBC典型运用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package nh.spring.tools.db;
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
 
public class TestDBConnection {
    /**
     * 典型jdbc连接
     * 1,与数据库建立连接
       2,发送SQL语句
       3,处理返回结果
     */
    static Connection con = null;
    static Statement stmt = null;
    static ResultSet rs = null;
     
    public static void main(String[] args) {   
        try {
            // 1、加载MYSQL驱动,这里MySQL的JDBC驱动类是com.mysql.jdbc.Driver,要求类路径中包含相应的Driver类
            Class.forName("com.mysql.jdbc.Driver").newInstance();
             
            // 2、连接到MYSQL,通过DriverManger来创建Connection对象,获取数据库连接
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/vShop", "root", "niuheng");
             
            // 3、创建Statement用以执行SQL语句,或者可以使用PreparedStatement
            Statement stmt = con.createStatement();
             
            // 4、执行SQL,获取结果
            ResultSet rs = stmt.executeQuery("select * from user");
            // 或者执行增删改操作,如:stmt.executeUpdate("delete * from blog");
             
            // 5、遍历并解析结果
            while (rs.next()) {
                long id = rs.getLong("id"); // 获取id列
                String username = rs.getString("username"); // 获取username列
                System.out.println("id:"+id+" Name:" +username);
            }
        } catch (Exception e) {
             
            // 如果有异常,进行异常处理
            System.out.print("MYSQL ERROR:" + e.getMessage());
             
        } finally {
            // 6、清理数据库连接相关的所有资源
            try {
                if (rs != null) {
                    rs.close();
                }
                 
                if (stmt != null) {
                    stmt.close();
                }
                 
                if (con != null) {
                    con.close();
                }
            } catch (SQLException ignored) {
                 
            }
        }
    }
 
}

  

posted @   hylinux  阅读(180)  评论(0编辑  收藏  举报
编辑推荐:
· 从二进制到误差:逐行拆解C语言浮点运算中的4008175468544之谜
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
阅读排行:
· 《HelloGitHub》第 108 期
· Windows桌面应用自动更新解决方案SharpUpdater5发布
· 我的家庭实验室服务器集群硬件清单
· C# 13 中的新增功能实操
· Supergateway:MCP服务器的远程调试与集成工具
点击右上角即可分享
微信分享提示