JDBC后台连接数据库

1 篇文章 0 订阅
0 篇文章 0 订阅

驱动程序名
public static String driverNmae = “com.mysql.jdbc.Driver”;

URL指向要访问的数据库名
public static String url = “jdbc:mysql://localhost/test? useUnicode=true&characterEncoding=UTF-8”;

MySQL配置时的用户名
public static String username = “root”;

MySQL配置时的密码
public static String password = “root”;

首先加载驱动程序
Class.forName(driverNmae);

声明Connection对象,获取连接并连接数据库
Connection con = DriverManager.getConnection(url,username,password);

1.获取Statemetn对象,用于执行SQL语句
Statement sta = con.createStatement();

2.预处理SQL语句
PreparedStatement stat = conn.prepareStatement(sql);

上述两种语句按情况使用
获取查询结果集(其中sql为查询语句)
ResultSet res = sta.executeQuery(sql);

关闭数据库
res = null;
sta = null;
con.close();

其次,上述语句都需要查看是否执行成功即有无异常出现(需要使用try和catch捕获异常情况)

PreparedStatement是预编译的,也就是说语句已经编译了,在执行操作时候,数据库管理系统不需要在对sql语句进行编辑,因此速度更快,适合批量的处理数据的操作,

如何只是执行几条数据操作,最好还是用statement,虽然PreparedStatement操作的比较快,但是系统开销 比较大。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值