How to connect to database with jdbc? (with code)
This article brings you how to connect jdbc to the database? (Attached is the code), which has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Introduction to JDBC
The full name of JDBC is: Java Data Base Connectivity (java database connection), which can provide unified access to a variety of databases . JDBC is a set of database access programming interfaces developed by sun. It is a SQL-level API. It is written in Java language, so it has good cross-platform characteristics. Database applications written using JDBC can run on any platform that supports Java without having to write different applications on different platforms. [Video tutorial recommendation: Java tutorial]
JDBC programming steps
(1) Load the driver:
Download the driver package: http://dev.mysql.com/downloads/connector/j/
Unzip and get the jar file. Copy this file to the Java project directory Java Resources/Libraries/, → buildpath.
(2) Obtain database connection
(3) Create Statement object:
(4) Send SQL command to database
(5 ) Process the returned results from the database (ResultSet class)
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();
}
}Prevent SQL injection and use 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();
}
}to code Optimize, set configuration files, tool classes, and implement additions and deletions.
Add configuration files to facilitate database modification and user login. . .
jdbc.properties (configuration file name)
driverName=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/testjdbc userName=root password=root
Note that when writing the configuration file, there cannot be spaces or quotation marks in the middle.
Tool class: Enhanced code complexity Usability
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);
}
}
}Test additions, deletions, modifications and checks:
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("查询成功");
}
}
}There are errors. Colleagues pointed out, thank you very much
The above is the entire content of this article, I hope it can be useful to everyone. Learning helps. For more exciting content, you can pay attention to the relevant tutorial columns of the PHP Chinese website! ! !
The above is the detailed content of How to connect to database with jdbc? (with code). For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undresser.AI Undress
AI-powered app for creating realistic nude photos
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undress AI Tool
Undress images for free
Clothoff.io
AI clothes remover
AI Hentai Generator
Generate AI Hentai for free.
Hot Article
Hot Tools
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
1378
52
After Java8 (291), TLS1.1 is disabled and JDBC cannot connect to SqlServer2008 using SSL. How to solve the problem?
May 16, 2023 pm 11:55 PM
After Java8-291, TLS1.1 is disabled, so that JDBC cannot connect to SqlServer2008 using SSL. What should I do? The following is the solution to modify the java.security file 1. Find the java.security file of jre. If it is jre, go to {JAVA_HOME}/jre/ In lib/security, for example????C:\ProgramFiles\Java\jre1.8.0_301\lib\security. If it is the Eclipse green installation-free portable version, search for java.security in the installation folder, such as????xxx\plugins \org
Java Errors: JDBC Errors, How to Solve and Avoid
Jun 24, 2023 pm 02:40 PM
With the widespread application of Java, JDBC errors often occur when Java programs connect to databases. JDBC (JavaDatabaseConnectivity) is a programming interface in Java used to connect to a database. Therefore, a JDBC error is an error encountered when a Java program interacts with a database. Here are some of the most common JDBC errors and how to solve and avoid them. ClassNotFoundException This is the most common JDBC
How to implement JDBC batch insert in Java
May 18, 2023 am 10:02 AM
1. Explain that in JDBC, the executeBatch method can execute multiple dml statements in batches, and the efficiency is much higher than executing executeUpdate individually. What is the principle? How to implement batch execution in mysql and oracle? This article will introduce to you the principle behind this. 2. Experiment introduction This experiment will be carried out through the following three steps: a. Record the time consuming of jdbc batch execution and single execution in mysql; b. Record the time consuming of jdbc batch execution and single execution in oracle; c. Record the batch execution and single execution of oracleplsql. The execution time-consuming related java and database versions are as follows: Java17, Mysql8, Oracle
Common problems encountered in Java using JDBC API to connect to MySQL database
Jun 10, 2023 am 09:55 AM
In recent years, the application of Java language has become more and more widespread, and JDBCAPI is a creative method for Java applications to interact with databases. JDBC is based on an open database connection standard called ODBC, which enables Java applications to connect to any database. management system (DBMS). Among them, MySQL is a popular database management system. However, developers will also encounter some common problems when connecting to MySQL databases. This article aims to introduce the JDBCAPI connection M
How to analyze JDBC programming in MySQL
May 30, 2023 pm 10:19 PM
1. Prerequisites for database programming Programming languages, such as Java, C, C++, Python and other databases, such as Oracle, MySQL, SQLServer and other database driver packages: Different databases provide different database driver packages corresponding to different programming languages. For example: MySQL provides the Java driver package mysql-connector-java, which is required to operate MySQL based on Java. Similarly, to operate Oracle database based on Java, Oracle's database driver package ojdbc is required. 2. Java database programming: JDBCJDBC, JavaDatabaseConnectiv
How to read the first few records in a database using PHP?
Mar 22, 2024 am 10:03 AM
How to read the first few records in a database using PHP? When developing web applications, we often need to read data from the database and display it to the user. Sometimes, we only need to display the first few records in the database, not the entire content. This article will teach you how to use PHP to read the first few records in the database and provide specific code examples. First, assume that you have connected to the database and selected the table you want to operate on. The following is a simple database connection example:
How to deal with SQLException when connecting to database in Java?
Jun 24, 2023 pm 09:23 PM
In Java programs, connecting to the database is a very common operation. Although ready-made class libraries and tools can be used to connect to the database, various abnormal situations may still occur during program development, among which SQLException is one of them. SQLException is an exception class provided by Java. It describes errors that occur when accessing the database, such as query statement errors, table non-existence, connection disconnection, etc. For Java programmers, especially those using JDBC (Java Data
What is the difference between Hibernate framework and JDBC?
Apr 17, 2024 am 10:33 AM
Differences between Hibernate and JDBC: Abstraction level: Hibernate provides high-level object mapping and query generation, while JDBC requires manual coding. Object-relational mapping: Hibernate maps Java objects and database tables, while JDBC does not provide this functionality. Query generation: Hibernate uses HQL to simplify query generation, while JDBC requires writing complex SQL queries. Transaction management: Hibernate automatically manages transactions, while JDBC requires manual management.


