数据库技术-JDBC连接MySQL_MySQL
bitsCN.com
数据库技术-JDBC连接MySQL
摘 要:JDBC(Java DataBase Connectivity,java数据库连接)是一种用于执行SQL语句的Java API,可以为多种关系数据库提供统一访问,它由一组用Java语言编写的类和接口组成。JDBC为数据库开发人员提供了一个标准的API,据此可以构建更高级的工具和接口,使数据库开发人员能够用纯Java API 编写数据库应用程序,并且可跨平台运行,并且不受数据库供应商的限制。
1、跨平台运行:这是继承了Java语言的“一次编译,到处运行”的特点;
2、不受数据库供应商的限制:巧妙在于JDBC设有两种接口,一个是面向应用程序层,其作用是使得开发人员通过SQL调用数据库和处理结果,而不需要考虑数据库的提供商;另一个是驱动程序层,处理与具体驱动程序的交互,JDBC驱动程序可以利用JDBC API创建Java程序和数据源之间的桥梁。应用程序只需要编写一次,便可以移到各种驱动程序上运行。Sun提供了一个驱动管理器,数据库供应商——如MySQL、Oracle,提供的驱动程序满足驱动管理器的要求就可以被识别,就可以正常工作。所以JDBC不受数据库供应商的限制。
JDBC API可以作为连接Java应用程序与各种关系数据库的纽带,在带来方便的同时也有负面影响,以下是JDBC的优、缺点。优点如下:
操作便捷:JDBC使得开发人员不需要再使用复杂的驱动器调用命令和函数; 可移植性强:JDBC支持不同的关系数据库,所以可以使同一个应用程序支持多个数据库的访问,只要加载相应的驱动程序即可; 通用性好:JDBC-ODBC桥接驱动器将JDBC函数换成ODBC; 面向对象:可以将常用的JDBC数据库连接封装成一个类,在使用的时候直接调用即可。
缺点如下:
访问数据记录的速度受到一定程度的影响; 更改数据源困难:JDBC可支持多种数据库,各种数据库之间的操作必有不同,这就给更改数据源带来了很大的麻烦
关键字:JDBC 数据库 MySQL
数据库技术-JDBC连接MySQL
一、JDBC连接数据库的流程及其原理
1、在开发环境中加载指定数据库的驱动程序。
MySQL支持JDBC的驱动程序的是:mysql-connector-java-5.1.18-bin.jar)
2、在Java程序中加载驱动程序。在Java程序中,
Class.forName(“指定数据库的驱动程序”)
Class.forName(“com.mysql.jdbc.Driver”)
3、创建数据连接对象
Connection connection = DriverManager.getConnection(“连接数据库的URL", "用户名","密码”)。URL=协议名+IP地址(域名)+端口+数据库名称;用户名和密码是指登录数据库时所使用的用户名和密码。
Connection connect =
DriverManager.geiConnection(“jdbc:mysql://localhost:3306/DatabaseName","root","123" )
4、创建Statement对象
Statement 类的主要是用于执行静态 SQL 语句并返回它所生成结果的对象。
Statement statament =connection.createStatement();
Statement statamentMySQL =connectMySQL.createStatement();
5、调用Statement对象的相关方法执行相对应的 SQL 语句
statement.excuteUpdate( "INSERTINTO table (name, age, sex,address, depart, worklen,wage)" + "VALUES ('Tom1', 321, 'M', 'china','Personnel','3','3000' ) ") ;
通过调用Statement对象的executeQuery()方法进行数据的查询,而查询结果会得到ResulSet对象,ResulSet表示执行查询数据库后返回的数据的集合,ResulSet对象具有可以指向当前数据行的指针。通过该对象的next()方法,使得指针指向下一行,然后将数据以列号或者字段名取出。如果当next()方法返回null,则表示下一行中没有数据存在。使用示例代码如下:
ResultSet resultSel =statement.executeQuery( "select * from table" );
6、关闭数据库连接:
Connection的close() 方法及时关闭数据连接。
finally { try { if (rs !=null) { rs.close(); } if (stmt !=null) { stmt.close(); } if (conn!=null) { conn.close(); } } catch (Exception e2) { System.out.println(e2.toString()); } }
二、演示
首先,MySQL数据库的准备
1、 我们需要知道MySQL的url user password
§ 注:查看方式:mysql> show variables
§
§ 或者通过其他MySQL辅助软件一目了然的看到本机MySQL的配置,我这里使用的是mysql workbench
§
§
§ 查看到我的
§ ipurl:localhost3308
§ user:root
§ password :123
§ 关于url 的localhost为数据库所在地址ip,本机mysql同样也在局域网中192.168.1.115 地址(也就是本机ip)
§ 查看方法:cmd->ipconfig
§
2、 打开MySQL建立一个数据库,进行jdbc连接的准备
§ 说明下我们的jdbc connection需要连接到某地址的某数据库
§ 格式参考Connection connect =
DriverManager.geiConnection(“jdbc:mysql://localhost:3306/DatabaseName","root" ,"123")
接下来建立数据库吧,
使用MySQL建立:
我建了个名叫zoo的数据库接下来可以进行java jdbc连接了。
1. 首先是倒入mysql的 jdbc驱动jar,
a) 工程下建立lib文件夹,放入mysql-connector-java的jar
b)
c) Add jars加入jar
d)
代码编写
package myjdbc;import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; public class Connn { public static void main(String[] args) throws SQLException { String user = "root"; String password = "123"; String url = "jdbc:mysql://localhost:3308/zoo"; String url2 = "jdbc:mysql://192.168.1.115:3308/zoo"; String url3 = "jdbc:mysql://localhost:3308/zoo?user=root&password=123&useUnicode=true&characterEncoding=8859_1"; String driver = "com.mysql.jdbc.Driver"; String tableName = "animal"; String sqlstr = "insert into animal (id,name,year) value("+5+","+"aiii"+","+33+");"; Connection conn = null; Statement stmt = null; ResultSet rs = null; try { Class.forName(driver); conn = DriverManager.getConnection(url3, "root", "123"); stmt = conn.createStatement(); System.out.println("数据库连接成功!"); } catch (ClassNotFoundException e) { System.out.println("数据库驱动不存在!"); System.out.println(e.toString()); } catch (SQLException e) { System.out.println("SQL错误"); System.out.println(e.toString()); } finally { try { if (rs != null) { rs.close(); } if (stmt != null) { stmt.close(); } if (conn != null) { conn.close(); } } catch (Exception e2) { System.out.println(e2.toString()); } } } }
连接成功!
三、总结
Jdbc 连接数据库不复杂,连接的模式已定义的很清晰,按照
Class.forName(“com.mysql.jdbc.Driver”) ->
DriverManager.getConnection ->
CreateStatement ->
rs进行操作
的方式就可以顺利进行。
注意容易出错的地方: DriverManager.getConnection 后面的写法比较多
1. String url = "jdbc:mysql://localhost:3308/zoo";
2. String url2 = "jdbc:mysql://192.168.1.115:3308/zoo";
3. String url3 = "jdbc:mysql://localhost:3308/zoo?user=root&password=123&useUnicode=true&characterEncoding=8859_1";
这几种都可以,主要是端口不要错,一般没有问题!
提供点帮助文件吧:
mysql-essential-5.6.0 下载地址 http://download.csdn.net/detail/zhangty0223/6811589
提供一个学习资料:
mysql从零开始学part1: http://download.csdn.net/detail/zhangty0223/6811667
mysql从零开始学part2: http://download.csdn.net/detail/zhangty0223/6811695
java jdbc mysql 驱动:http://download.csdn.net/detail/zhangty0223/6819387
整个工程源码:http://download.csdn.net/detail/zhangty0223/6819457
谢谢!
2014.1.7
以上就是数据库技术-JDBC连接MySQL_MySQL的内容,更多相关内容请关注PHP中文网(www.php.cn)!

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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

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











The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

MySQL and phpMyAdmin are powerful database management tools. 1) MySQL is used to create databases and tables, and to execute DML and SQL queries. 2) phpMyAdmin provides an intuitive interface for database management, table structure management, data operations and user permission management.

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

I encountered a tricky problem when developing a small application: the need to quickly integrate a lightweight database operation library. After trying multiple libraries, I found that they either have too much functionality or are not very compatible. Eventually, I found minii/db, a simplified version based on Yii2 that solved my problem perfectly.

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

The basic operations of MySQL include creating databases, tables, and using SQL to perform CRUD operations on data. 1. Create a database: CREATEDATABASEmy_first_db; 2. Create a table: CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY, titleVARCHAR(100)NOTNULL, authorVARCHAR(100)NOTNULL, published_yearINT); 3. Insert data: INSERTINTObooks(title, author, published_year)VA

When developing an e-commerce website using Thelia, I encountered a tricky problem: MySQL mode is not set properly, causing some features to not function properly. After some exploration, I found a module called TheliaMySQLModesChecker, which is able to automatically fix the MySQL pattern required by Thelia, completely solving my troubles.
