ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

JDBC的详解

2021-12-04 21:31:59  阅读:136  来源: 互联网

标签:studentId String int JDBC studentPhone studentAge 详解 studentName


在这里插入图片描述JDBC(Java Database Connectivity),即Java数据库连接,是一种用于执行SQL语句的Java API,可以为多种关系数据库提供同一访问,它由一组用Java语言编写的类和接口组成。JDBC提供了一种基准,根据这种基准可以构建更高级的工具和接口,使数据库开发人员能够编写数据库应用程序。总而言之,JDBC做了三件事:
1、与数据库建立连接2、发送操作数据库的语句3、处理结果 JDBC简单示例下面的代码演示了如何利用JDBC从数据库中查询若干条符合要求的数据出来,使用的数据库是MySql。1、建立一个数据库和一张表,我的习惯是在CLASSPATH底下建立一个.sql的文件用于存放sql语句复制代码create database school;use school;create table student( studentId int primary key auto_increment not null, studentName varchar(10) not null, studentAge int, studentPhone varchar(15))insert into student values(null,‘Betty’, ‘20’, ‘00000000’);insert into student values(null,‘Jerry’, ‘18’, ‘11111111’);insert into student values(null,‘Betty’, ‘21’, ‘22222222’);insert into student values(null,‘Steve’, ‘27’, ‘33333333’);insert into student values(null,‘James’, ‘22’, ‘44444444’);commit;复制代码2、建立一个.properties文件用于存储MySql连接的几个属性。为什么要建立.properties而不在代码里面写死,由于这个并不是Java设计模式的分类,就不细讲了,只需要记住:从设计的角度看,把内容写在配置文件中永远好过把内容写死在代码中。mysqlpackage=com.mysql.jdbc.Drivermysqlurl=jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=utf-8mysqlname=rootmysqlpassword=root3、根据表字段建立实体类复制代码public class Student{ private int studentId; private String studentName; private int studentAge; private String studentPhone; public Student(int studentId, String studentName, int studentAge, String studentPhone) { this.studentId = studentId; this.studentName = studentName; this.studentAge = studentAge; this.studentPhone = studentPhone; } public int getStudentId() { return studentId; } public String getStudentName() { return studentName; } public int getStudentAge() { return studentAge; } public String getStudentPhone() { return studentPhone; } public String toString() { return "studentId = " + studentId + ", studentName = " + studentName + ", studentAge = " + studentAge + ", studentPhone = " + studentPhone; }}复制代码4、写一个DBConnection类专门用于向外提供数据库连接。我这里用了MySql,所以只有一个mysqlConnection,如果还用到了Oracle,当然还可以向外提供一个oracleConnection。把这些连接设为全局的可能有人会想是否会有线程安全问题,这是一个很好的问题。那因为我们只从Connection里面读取一个PreparedStatement出来,而不会去写它,只读不修改,是不会引发线程安全问题的。另外把Connection设置为static的保证了Connection在内存中只有一份,不会占多大资源,每次使用完不调用close()方法去关闭它也没事。

标签:studentId,String,int,JDBC,studentPhone,studentAge,详解,studentName
来源: https://blog.csdn.net/weixin_57763462/article/details/121722067

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有