jdbc链接数据库
JDBC简介
JDBC全称为:Java Data Base Connectivity (java数据库连接),可以为多种数据库提供填统一的访问。JDBC是sun开发的一套数据库访问编程接口,是一种SQL级的API。它是由java语言编写完成,所以具有很好的跨平台特性,使用JDBC编写的数据库应用程序可以在任何支持java的平台上运行,而不必在不同的平台上编写不同的应用程序。
JDBC编程步骤
(1)加载驱动程序:
下载驱动包 : http://dev.mysql.com/downloads/connector/j/
解压,得到 jar文件。将该文件复制到Java工程目录Java Resources/Libraries/ 下,→ buildpath 。
(2)获得数据库连接
(3)创建Statement对象:
(4)向数据库发送SQL命令
(5)处理数据库的返回结果(ResultSet类)
package com.baidu.emp.jdbcTest; import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement; import com.mysql.jdbc.Driver;
/**
* 开始使用jdbc连接数据库
* @author Admin
*
*/
public class Test001 { public static void main(String[] args) throws Exception { /**
* 加载驱动
*/
// 方法一:
/*
* import java.sql.DriverManager; import com.mysql.jdbc.Driver;
*/
// Driver driver = new Driver();
// DriverManager.registerDriver(driver); // 方法二:(推荐使用)
Class.forName("com.mysql.jdbc.Driver"); /**
* 创建链接
*/
String url = "jdbc:mysql://localhost:3306/testjdbc";
String user = "root";
String password = "root";
Connection connection = DriverManager.getConnection(url, user, password); // 创建statement对象
Statement statement = connection.createStatement(); /**
* 执行SQL,获取结果集
*/
String sql = "select * from test01";
ResultSet result = statement.executeQuery(sql); // 遍历结果集
while (result.next()) {
String name = result.getString("name");
int id = result.getInt("id");
System.out.println(name + "\t" + id);
} /**
* 关闭链接,释放资源
*/
result.close();
statement.close();
connection.close();
}
}
防止SQL注入改用prepareStatement
package com.boya.emp.jdbcTest; import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
/**
* SQL注入,使用prepareStatement对象进行预编译
* @author Admin
*
*/
public class Test002 { public static void main(String[] args) throws Exception { /**
* 加载驱动
*/
Class.forName("com.mysql.jdbc.Driver"); /**
* 创建链接
*/
String url = "jdbc:mysql://localhost:3306/testjdbc";
String user = "root";
String password = "root";
Connection connection = DriverManager.getConnection(url, user, password); // 写SQL
String sql = "select * from test01 where id = ?";
//创建statement对象,预编译
PreparedStatement statement = connection.prepareStatement(sql);
//设置参数
statement.setInt(1, 2);
/**
* 执行SQL,获取结果集
*/
ResultSet result = statement.executeQuery(); // 遍历结果集
while (result.next()) {
String name = result.getString("name");
int id = result.getInt("id");
System.out.println(name + "\t" + id);
} /**
* 关闭链接,释放资源
*/
result.close();
statement.close();
connection.close();
}
}
进行代码优化,设置配置文件,工具类,实现增删该查
增加配置文件方便修改数据库,用户登录。。。
jdbc.properties(配置文件名)
driverName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/testjdbc
userName=root
password=root
注意写配置文件时中间不可以有空格,引号之类的
工具类:增强了代码的复用性
package com.baidu.emp.utils; import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties; import org.junit.Test; public class JdbcUtils { static String driverClassName;
static String url;
static String user;
static String password; static {
// 创建配置文件对象
Properties properties = new Properties();
// 加载配置文件输入流
InputStream inputStream = JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
// 重新加载配置文件
try {
properties.load(inputStream);
// 获取配置文件的值
driverClassName = properties.getProperty("driverName");
url = properties.getProperty("url");
user = properties.getProperty("userName");
password = properties.getProperty("password");
Class.forName(driverClassName); } catch (Exception e) {
// 抛出异常
throw new RuntimeException(e);
}
} /**
* 获取连接
*/
@Test
public void testName() throws Exception { System.out.println(driverClassName);
}
public static Connection getConnection() {
Connection connection = null;
try {
connection = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
// 抛出异常
throw new RuntimeException(e);
}
return connection;
} /**
* 关闭链接,释放资源
*/
public static void close(Connection connection, PreparedStatement statement, ResultSet resultSet) { try {
if (resultSet != null) {
resultSet.close();
}
resultSet = null; // 垃圾及时清除
//注意,不要弄成死循环
close(connection, statement);
} catch (SQLException e) {
throw new RuntimeException(e);
} } /**
* 增删改释放资源
*/
public static void close(Connection connection, PreparedStatement statement) { try {
if (connection != null) {
connection.close();
} connection = null;
if (statement != null) {
statement.close();
}
statement = null; } catch (SQLException e) {
throw new RuntimeException(e);
} } }
测试增删改查:
package com.baidu.emp.jdbcTest; import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet; import org.junit.After;
import org.junit.Before;
import org.junit.Test; import com.baidu.emp.utils.JdbcUtils; /**
* 使用jdbcUtils连接数据库进行增删改查
*
* @author Admin
*
*/
public class Test003 { // 初始化值
Connection connection = null;
PreparedStatement statement = null;
ResultSet result = null; @Before
public void start() throws Exception {
// 创建链接
connection = JdbcUtils.getConnection();
System.out.println("创建链接");
} @After
public void end() throws Exception {
// 关闭链接
JdbcUtils.close(connection, statement, result);
System.out.println("关闭链接");
} /**
*插入数据
* @throws Exception
*/
@Test
public void add() throws Exception {
String sql = "insert into test01 values(null,?)";
statement = connection.prepareStatement(sql);
statement.setString(1, "李四");
int result = statement.executeUpdate();
if (result!=0) {
System.out.println("添加成功");
}
}
/**
* 删除数据
* @throws Exception
*/
@Test
public void del() throws Exception {
String sql = "delete from test01 where id =?";
statement = connection.prepareStatement(sql);
statement.setInt(1,3);
int result = statement.executeUpdate();
if (result!=0) {
System.out.println("删除成功");
}
}
/**
* 修改数据
* @throws Exception
*/
@Test
public void change() throws Exception {
String sql = "update test01 set name = ? where id = ?";
statement = connection.prepareStatement(sql);
statement.setString(1, "张飞");
statement.setInt(2, 2);
int result = statement.executeUpdate();
if (result!=0) {
System.out.println("修改成功");
}
} /**
* 查询全部数据
* @throws Exception
*/
@Test
public void findAll() throws Exception {
String sql = "select id , name from test01";
statement = connection.prepareStatement(sql);
result = statement.executeQuery();
if (result.next()) {
System.out.println("查询成功");
}
} /**
* 条件查询数据
* @throws Exception
*/
@Test
public void findOne() throws Exception {
String sql = "select id , name from test01 where id = ?";
statement = connection.prepareStatement(sql);
statement.setInt(1, 2);
result = statement.executeQuery();
if (result.next()) {
System.out.println("查询成功");
}
} }
希望能给大家一个参考,也希望大家多多支持我。
jdbc链接数据库的更多相关文章
- 4、原生jdbc链接数据库常用资源名
原生jdbc链接数据库要素:#MySql:String url="jdbc:mysql://localhost:3306/数据库名";String name="root& ...
- jdbc链接数据库,获取表名,字段名和数据
import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import ...
- JDBC链接数据库步骤
java中定义链接数据库的标准:JDBC 1.导包:不同数据库有不同的jdbc驱动包,而且jdbc驱动包和数据库版本必须对应 2.测试 3.写代码 try { 1.//加载JDBC驱动 Clas ...
- jdbc链接数据库的三种方式
/** * jdbc连接数据库 * @author APPle * */ public class Demo1 { //连接数据库的URL private String url = "jdb ...
- 1019 JDBC链接数据库进行修删改查
package com.liu.test01; import java.sql.Statement; import java.sql.Connection; import java.sql.Drive ...
- JDBC链接数据库。
第一步,创建一个空包: 给包起个名字: 新建Modules: 给Modules起名: 创建libs文件: 点击file---->new---->project---->Directo ...
- 如何使用JDBC链接数据库
1.加载数据库驱动 不同的数据库加载的驱动不一样 Class.forName(com.MySQL.jdbc.Driver) Class.forName(oracle.jdbc.driver.Oracl ...
- Java JDBC链接数据库
1.注册驱动Class.forname("com.mysql.jdbc.Driver");//这是连接mysql数据库的驱动2.获取数据库连接java.sql.Connectio ...
- Java 项目JDBC 链接数据库中会出现的错误
1.出现的地方 package com.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql ...
随机推荐
- 要想学好Java编程,构造器、方法重载、this关键字、垃圾回收机制,这4关一定要过!
有人说,你应该关注时事.财经,甚至流行的电影.电视剧,才有可能趁着热点写出爆文:有人说,你别再写“无聊”的技术文了,因为程序员的圈子真的很小,即便是像鸿洋那样的招牌大牛,文章是那么的干货,浏览量有多少 ...
- Vue轻松入门,一起学起来!
我们创建一个项目,这个项目我们细说Vue. 一.如何在项目中添加模块 我们通过npm 进行 安装 模块. 首先我们通过cmd.exe cd进入你的项目根目录,必须存在package.json文件,安装 ...
- 说一说MVC的Authentication过滤(四)
前沿: 一般情况下,在我们做访问权限管理的时候,会把用户的正确登录后的基本信息保存在Session中,以后用户每次请求页面或接口数据的时候,拿到 Session中存储的用户基本信息,查看比较他有没有登 ...
- Redis分区
数据是怎样分布在多个Redis实例上的 分区是将你的数据分布在多个Redis实例上,以至于每个实例只包含一部分数据. 为什么分区是有用的呢 Redis分区有两个主要目标: 它允许更大的数据库,用许多计 ...
- Centos7 防火墙 firewalld 实用操作
一.前言 Centos7以上的发行版都试自带了firewalld防火墙的,firewalld去带了iptables防火墙.其原因是iptables的防火墙策略是交由内核层面的netfilter网络过滤 ...
- C#版 - Leetcode 13. 罗马数字转整数 - 题解
C#版 - Leetcode 13. 罗马数字转整数 - 题解 Leetcode 13. Roman to Integer 在线提交: https://leetcode.com/problems/ro ...
- spring boot MySQL极简封装
摒弃繁琐配置,采用极简方式,源码简单,调用丰富,无污染,易携带,工作量减半,java操作mysql居家旅行升职加薪登上人生巅峰迎娶白富美必备object! 项目地址:https://gitee.com ...
- Kafka基础入门
1. Kafka简介 Kafka是由Apache软件基金会开发的一个开源流处理平台,由Scala和Java编写.Kafka是一种高吞吐量的分布式发布订阅消息系统,它可以处理消费者规模的网站中的所有动作 ...
- Cglib动态代理浅析
原文同步发表至个人博客[夜月归途] 原文链接:http://www.guitu18.com/se/java/2018-06-29/18.html 作者:夜月归途 出处:http://www.guitu ...
- Docker入门(一)用hello world入门docker
初识Docker Docker是什么? Docker 是一个开源的应用容器引擎,基于 Go 语言并遵从Apache2.0协议开源. Docker 可以让开发者打包他们的应用以及依赖包到一个轻量 ...