This article brings you relevant knowledge about mysql, which mainly organizes the related issues of JDBC programming knowledge points. JDBC (Java DataBase Connectivity, java database connection) is a kind of The Java API that executes SQL statements can provide unified access to a variety of relational databases. It consists of a set of classes and interfaces written in the Java language. Let's take a look at it together. I hope it will be helpful to everyone.
Recommended learning: mysql video tutorial
This article will introduce JDBC programming, JDBC (Java DataBase Connectivity, java database connection ) is a Java API for executing SQL statements that can provide unified access to a variety of relational databases. It consists of a set of classes and interfaces written in the Java language.
We can download the MySQL jdbc driver package from the official website, or we can download it from the maven central warehouse. This What is the maven central warehouse? You can think of it as the "app store" software in our mobile phones. Its function is similar to that of the app store, except that the mobile app store contains mobile software, while the maven central warehouse contains many APIs and dependency packages.
Now that MySQL has been acquired by Oracle, Oracle's "food appearance" is a bit ugly. You can find it from the official website, but I feel that the maven central warehouse is easier to find, so we go to the maven central warehouse to download the jdbc driver package.
Website: maven central warehouse
The first step is to click on the website to enter the maven central warehouse.
The second step is to search for MySQL and select the one shown below.
The third step is to click to enter and find the jdbc driver package corresponding to the major version. If your MySQL is version 5, then choose version 5 for the driver package. Of course, if your MySQL is version Summary of MySQL database JDBC programming knowledge points, Then select version Summary of MySQL database JDBC programming knowledge points for your driver package.
My MySQL is version 5, so I choose the driver package with the largest version 5.
The fourth step is to click in and follow the steps below to download the driver package.
Once the download is complete our driver package is ready.
Use the compiler to create a project. After the project is created, follow the steps below:
The first step is to create a directory with a random name. , might as well be called the lib
directory.
The second step is to copy the downloaded driver package to this directory.
The third step is to set options, right-click the directory you just created and copied the driver package to, and find As a Lib...# # In this way, our driver package will be imported into our project, and then we can write jdbc code.
DataSource object to describe where the database is.
DataSource dataSource = new MysqlDataSource();
DataSource is a jdbc interface in
java.sql,
MysqlDataSource is the source and an implementation in the driver package we downloaded
DataSourceInterface class.
//设置数据库所在地址 ((MysqlDataSource)dataSource).setURL("jdbc:mysql://Summary of MySQL database JDBC programming knowledge pointsSummary of MySQL database JDBC programming knowledge pointsSummary of MySQL database JDBC programming knowledge points.0.0.Summary of MySQL database JDBC programming knowledge points:Summary of MySQL database JDBC programming knowledge pointsSummary of MySQL database JDBC programming knowledge points06/jdbctest/characterEncoding=utfSummary of MySQL database JDBC programming knowledge points&useSSL=false"); //设置登录数据库的账户名 ((MysqlDataSource)dataSource).setUser("root"); //设置登录数据库的密码 ((MysqlDataSource)dataSource).setPassword("Summary of MySQL database JDBC programming knowledge pointsSummary of MySQL database JDBC programming knowledge pointsSummary of MySQL database JDBC programming knowledge pointsSummary of MySQL database JDBC programming knowledge points56");
jdbc:mysql://Summary of MySQL database JDBC programming knowledge pointsSummary of MySQL database JDBC programming knowledge pointsSummary of MySQL database JDBC programming knowledge points.0.0.Summary of MySQL database JDBC programming knowledge points:Summary of MySQL database JDBC programming knowledge pointsSummary of MySQL database JDBC programming knowledge points06/jdbctest?characterEncoding=utfSummary of MySQL database JDBC programming knowledge points&useSSL=false is a URL, also called a unique resource locator.
jdbc:mysql means that the
url is the URL for jdbc mysql. Because there are many databases, not just jdbc, it needs to be subdivided.
URL type statement://database address/database name?Character set encoding&whether to encrypt.
DataSource object, call the
getConnection()## of the object. #Method, obtain the java.sql.Connection
object, thus establishing a connection with the database. <pre class="brush:php;toolbar:false">Connection connection = dataSource.getConnection();</pre>
<hsummary of mysql database jdbc programming knowledge points>Summary of MySQL database JDBC programming knowledge points.Summary of MySQL database JDBC programming knowledge points构造并执行sql语句(插入操作为例)</hsummary>of MySQL database JDBC programming knowledge points><p>第四步,构造<code>sql
语句字符串,并将该语句包装成PreparedStatement
对象,即调用Connection
对象的prepareStatement
方法,参数是sql字符串,会返回一个PreparedStatement
对象,然后我们再调用PreparedStatement
对象中的executeUpdate
方法或executeQuery
方法执行sql
语句。
我们先以插入操作为例。
//操作数据库 关键在于构造sql语句 //jdbc 构造的sql语句不需要带上; String sql = "insert into student values(Summary of MySQL database JDBC programming knowledge points, Summary of MySQL database JDBC programming knowledge points9;张三Summary of MySQL database JDBC programming knowledge points9;)"; //将sql字符串包装成一个语句对象,表示待执行的sql的对象 PreparedStatement statement = connection.prepareStatement(sql); //执行sql //如果待执行的sql语句操作是insert, update, delete,则使用executeUpdate方法执行,返回值为影响数据的行数 //如果待执行的sql语句操作是select,则使用executeQuery方法执行 int ret = statement.executeUpdate();
其中,如果待执行的sql语句操作是insert, update, delete,则使用executeUpdate方法执行,返回值为影响数据的行数,如果待执行的sql语句操作是select,则使用executeQuery方法执行,返回值是一个ResultSet
结果表对象。
第五步,释放资源,我们执行完毕sql语句后需要及时地将资源释放,在JDBC编程中,最常见需要释放的类或接口有三个,分别是Connection
,PreparedStatement
,ResultSet
,其中前面两个在jdbc插入操作中已经使用过了,而最后一个,即ResultSet
,它是在执行查询语句需要用到的,调用executeQuery
方法执行查询语句之后,会返回一个“临时表”,该“临时表”上储存了查询的结果,我们可以通过遍历该结果表来获取查询数据库的结果。
//此时sql语句已经执行完毕了,需要释放资源statement.close();connection.close();
使用jdbc编程进行插入操作全部代码:
import com.mysql.jdbc.jdbcSummary of MySQL database JDBC programming knowledge points.optional.MysqlDataSource;import javax.sql.DataSource;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.SQLException;import java.util.Scanner;public class TestJdbc { public static void main(String[] args) throws SQLException { DataSource dataSource = new MysqlDataSource(); //设置数据库所在地址 ((MysqlDataSource)dataSource).setURL("jdbc:mysql://Summary of MySQL database JDBC programming knowledge pointsSummary of MySQL database JDBC programming knowledge pointsSummary of MySQL database JDBC programming knowledge points.0.0.Summary of MySQL database JDBC programming knowledge points:Summary of MySQL database JDBC programming knowledge pointsSummary of MySQL database JDBC programming knowledge points06/jdbctest?characterEncoding=utfSummary of MySQL database JDBC programming knowledge points&useSSL=false"); //设置登录数据库的账户名 ((MysqlDataSource)dataSource).setUser("root"); //设置登录数据库的密码 ((MysqlDataSource)dataSource).setPassword("Summary of MySQL database JDBC programming knowledge pointsSummary of MySQL database JDBC programming knowledge pointsSummary of MySQL database JDBC programming knowledge pointsSummary of MySQL database JDBC programming knowledge points56"); //建立连接 Connection connection = dataSource.getConnection(); //操作数据库 关键在于构造sql语句 //jdbc 构造的sql语句不需要带上; String sql = "insert into student values(Summary of MySQL database JDBC programming knowledge points, Summary of MySQL database JDBC programming knowledge points9;张三Summary of MySQL database JDBC programming knowledge points9;)"; //将sql字符串包装成一个语句对象,表示待执行的sql的对象 PreparedStatement statement = connection.prepareStatement(sql); //执行sql //如果待执行的sql语句操作是insert, update, delete,则使用executeUpdate方法执行,返回值为影响数据的行数 //如果待执行的sql语句操作是select,则使用executeQuery方法执行 int ret = statement.executeUpdate(); //此时sql语句已经执行完毕了,需要释放资源 statement.close(); connection.close(); }}
运行结果,我们通过查询数据库的表的结果来进行观察:
mysql> create database jdbctest;Query OK, Summary of MySQL database JDBC programming knowledge points row affected (0.0Summary of MySQL database JDBC programming knowledge points sec)mysql> use jdbctest;Database changed mysql> create table student(id int, name varchar(Summary of MySQL database JDBC programming knowledge points0));Query OK, 0 rows affected (0.0Summary of MySQL database JDBC programming knowledge points sec)mysql> show tables;+--------------------+| Tables_in_jdbctest |+--------------------+| student |+--------------------+Summary of MySQL database JDBC programming knowledge points row in set (0.00 sec)-- 执行jdbc代码后查询mysql> select * from student;+------+--------+| id | name |+------+--------+| Summary of MySQL database JDBC programming knowledge points | 张三 |+------+--------+Summary of MySQL database JDBC programming knowledge points row in set (0.00 sec)
程序运行结果,表示Summary of MySQL database JDBC programming knowledge points行受到了影响。
我们发现我们的sql语句是完完全全写死的,这一点不好,我们可以使用输入的操作让用户输入信息进行插入,那就需要使用到Scanner
类了。
我们得到用户输入的信息后,我们需要对信息进行整合,最容易想到的方式就是字符串拼接,但是这么做有如下的缺点,一是容易写错,特别是单双引号比较多的情况下,二是不安全,黑客可以使用sql注入的方式来修改数据库。
所以更好的方法就是把sql字符串中待输入的信息使用?
来代替或者叫做占位,然后通过PreparedStatement
中的setXXX
系列方法来逐个设置每个?
的内容是什么。
这个系列的方法,第一个参数表示sql待执行对象中第多少个?
,第二个参数表示将这个?
设置的内容。比如:
//操作数据库 关键在于构造sql语句 //jdbc 构造的sql语句不需要带上; String sql = "insert into student values(?, ?)"; //将sql字符串包装成一个语句对象,表示待执行的sql的对象 PreparedStatement statement = connection.prepareStatement(sql); statement.setInt(Summary of MySQL database JDBC programming knowledge points, id); statement.setString(Summary of MySQL database JDBC programming knowledge points, name);
完整代码:jdbc插入操作源代码
运行结果:
数据库查询结果:
mysql> select * from student;+------+--------+| id | name |+------+--------+| Summary of MySQL database JDBC programming knowledge points | 张三 || Summary of MySQL database JDBC programming knowledge points | 李四 |+------+--------+Summary of MySQL database JDBC programming knowledge points rows in set (0.00 sec)
在jdbc编程中,删除操作和更新操作,它的步骤与插入操作是一模一样的,只不过就是构造的sql
语句不一样,其他都一样。
删除操作关键代码:
//用户输入 System.out.println("请输入需要删除的学号:"); int id = sc.nextInt(); //操作数据库 关键在于构造sql语句 //jdbc 构造的sql语句不需要带上; String sql = "delete from student where id = ?"; PreparedStatement statement = connection.prepareStatement(sql); statement.setInt(Summary of MySQL database JDBC programming knowledge points, id); System.out.println("statement" + statement);
jdbc删除操作完整代码:源代码地址
程序运行结果:
数据库查询结果:
mysql> select * from student;+------+--------+| id | name |+------+--------+| Summary of MySQL database JDBC programming knowledge points | 张三 |+------+--------+Summary of MySQL database JDBC programming knowledge points row in set (0.00 sec)
更新操作关键代码:
//用户输入 需要修改的id 与修改后的姓名 System.out.println("请输入需要修改的学号:"); int id = sc.nextInt(); sc.nextLine(); System.out.println("请输入修改后的姓名:"); String afterName = sc.nextLine(); //操作数据库 关键在于构造sql语句 //jdbc 构造的sql语句不需要带上; String sql = "update student set name = ? where id = ?"; PreparedStatement statement = connection.prepareStatement(sql); statement.setString(Summary of MySQL database JDBC programming knowledge points, afterName); statement.setInt(Summary of MySQL database JDBC programming knowledge points, id); System.out.println("statement" + statement);
jdbc更新操作完整代码:源代码地址
程序运行结果:
数据库查询结果:
mysql> select * from student;+------+--------+| id | name |+------+--------+| Summary of MySQL database JDBC programming knowledge points | 王五 |+------+--------+Summary of MySQL database JDBC programming knowledge points row in set (0.00 sec)
jdbc的查询操作与插入删除更新操作有一点点不同,执行查询sql语句的时候是调用executeQuery
方法来执行语句的,并且会带回查询的结果,我们可以通过类似与迭代器的操作来获取查询的结果,这个结果集使用完后需要将它释放。
关键代码:
//操作数据库 关键在于构造sql语句 //jdbc 构造的sql语句不需要带上; String sql = "select * from student"; PreparedStatement statement = connection.prepareStatement(sql); //执行sql 查询操作返回的不是int 而是一个临时表 使用ResultSet对象表示这个临时表 ResultSet ret = statement.executeQuery(); //便利结果集合 //预期结果格式// +------+--------+// | id | name |// +------+--------+// | Summary of MySQL database JDBC programming knowledge points | 王五 |// +------+--------+ while (ret.next()) { int id = ret.getInt("id"); String name = ret.getString("name"); System.out.println("id:" + id + ", name:" + name); } //关闭资源 ret.close(); statement.close(); connection.close();
jdbc查询操作完代码:源代码地址
程序运行结果:
好了,JDBC的全部内容差不多就是这一些,所有的完整代码链接:地址。
推荐学习:mysql视频教程
The above is the detailed content of Summary of MySQL database JDBC programming knowledge points. For more information, please follow other related articles on the PHP Chinese website!

MySQL index cardinality has a significant impact on query performance: 1. High cardinality index can more effectively narrow the data range and improve query efficiency; 2. Low cardinality index may lead to full table scanning and reduce query performance; 3. In joint index, high cardinality sequences should be placed in front to optimize query.

The MySQL learning path includes basic knowledge, core concepts, usage examples, and optimization techniques. 1) Understand basic concepts such as tables, rows, columns, and SQL queries. 2) Learn the definition, working principles and advantages of MySQL. 3) Master basic CRUD operations and advanced usage, such as indexes and stored procedures. 4) Familiar with common error debugging and performance optimization suggestions, such as rational use of indexes and optimization queries. Through these steps, you will have a full grasp of the use and optimization of MySQL.

MySQL's real-world applications include basic database design and complex query optimization. 1) Basic usage: used to store and manage user data, such as inserting, querying, updating and deleting user information. 2) Advanced usage: Handle complex business logic, such as order and inventory management of e-commerce platforms. 3) Performance optimization: Improve performance by rationally using indexes, partition tables and query caches.

SQL commands in MySQL can be divided into categories such as DDL, DML, DQL, DCL, etc., and are used to create, modify, delete databases and tables, insert, update, delete data, and perform complex query operations. 1. Basic usage includes CREATETABLE creation table, INSERTINTO insert data, and SELECT query data. 2. Advanced usage involves JOIN for table joins, subqueries and GROUPBY for data aggregation. 3. Common errors such as syntax errors, data type mismatch and permission problems can be debugged through syntax checking, data type conversion and permission management. 4. Performance optimization suggestions include using indexes, avoiding full table scanning, optimizing JOIN operations and using transactions to ensure data consistency.

InnoDB achieves atomicity through undolog, consistency and isolation through locking mechanism and MVCC, and persistence through redolog. 1) Atomicity: Use undolog to record the original data to ensure that the transaction can be rolled back. 2) Consistency: Ensure the data consistency through row-level locking and MVCC. 3) Isolation: Supports multiple isolation levels, and REPEATABLEREAD is used by default. 4) Persistence: Use redolog to record modifications to ensure that data is saved for a long time.

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

MySQL is suitable for small and large enterprises. 1) Small businesses can use MySQL for basic data management, such as storing customer information. 2) Large enterprises can use MySQL to process massive data and complex business logic to optimize query performance and transaction processing.

InnoDB effectively prevents phantom reading through Next-KeyLocking mechanism. 1) Next-KeyLocking combines row lock and gap lock to lock records and their gaps to prevent new records from being inserted. 2) In practical applications, by optimizing query and adjusting isolation levels, lock competition can be reduced and concurrency performance can be improved.


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

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),