search
HomeDatabaseMysql TutorialJava连接MYSQL 数据库的连接步骤

此文章主要向大家描述的是Java连接MYSQL 数据库(以MySQL为例)的实际操作步骤,我们是以相关实例的方式来引出Java连接MYSQL 数据库的实际操作流程,以下就是文章的主要内容描述。 当然,首先要安装有JDK(一般是JDK1.5.X)。然后安装MySQL,这些都比较简单,具

此文章主要向大家描述的是Java连接MYSQL 数据库(以MySQL为例)的实际操作步骤,我们是以相关实例的方式来引出Java连接MYSQL 数据库的实际操作流程,以下就是文章的主要内容描述。

当然,首先要安装有JDK(一般是JDK1.5.X)。然后安装MySQL,这些都比较简单,具体过程就不说了。配置好这两个环境后,下载JDBC驱动mysql-connector-java-5.0.5.zip(这个是最新版的)。然后将其解压缩到任一目录。我是解压到D盘,然后将其目录下的mysql-connector-java-5.0.5-bin.jar加到classpath里,

具体如下:“我的电脑”-> “属性” -> “高级” -> “环境变量”,在系统变量那里编辑classpath,将D:\mysql-connector-java-5.0.5\mysql-connector-java-5.0.5-bin.jar加到最后,在加这个字符串前要加“;”,以与前一个classpath区分开。然后确定。

环境配置好了,很简单。现在,先配置Java连接MySQL,设其用户名为“root”,密码为“root”。在命令行或用一个SQL的前端软件创建Database。

我是用SQLyog的前端软件来创建Database的。

先创建数据库:

<ol><li><span><span>CREATE DATABASE SCUTCS; </span></span></li></ol>

接着,创建表:

<ol>
<li><span><span>CREATE TABLE STUDENT  </span></span></li>
<li><span>(  </span></li>
<li><span>SNO CHAR(7) NOT NULL,  </span></li>
<li><span>SNAME VARCHAR(8) NOT NULL,  </span></li>
<li><span>SEX CHAR(2) NOT NULL,  </span></li>
<li><span>BDATE DATE NOT NULL,  </span></li>
<li><span>HEIGHT DEC(5,2) DEFAULT 000.00,  </span></li>
<li><span>PRIMARY KEY(SNO)  </span></li>
<li><span>);  </span></li>
</ol>

然后插入数据,可以用SQL语句insert into values (value1, value2, ...);

也可以用SQLyog来操作

好了,创建好了。

下面,我们来编写.java文件来演示一下如何访问Java连接MySQL数据库。

<ol>
<li><span><span>import java.sql.*;   </span></span></li>
<li><span>public class JDBCTest {   </span></li>
<li><span>public static void main(String[] args){  </span></li>
</ol>

驱动程序名

String driver = "com.mysql.jdbc.Driver";

// URL指向要访问的数据库名scutcs

String url = "jdbc:mysql://127.0.0.1:3306/scutcs";

// MySQL配置时的用户名

String user = "root";

// Java连接MySQL配置时的密码

String password = "root";

try {

// 加载驱动程序

Class.forName(driver);

// 连续数据库

Connection conn = DriverManager.getConnection(url, user, password);

if(!conn.isClosed())

System.out.println("Succeeded connecting to the Database!");

// statement用来执行SQL语句

Statement statement = conn.createStatement();

// 要执行的SQL语句

String sql = "select * from student";

结果集

<ol>
<li><span><span>ResultSet </span><span>rs</span><span> = </span><span>statement</span><span>.executeQuery(sql);  </span></span></li>
<li><span>System.out.println("-----------------");  </span></li>
<li><span>System.out.println("执行结果如下所示:");  </span></li>
<li><span>System.out.println("-----------------");  </span></li>
<li><span>System.out.println(" 学号" + "\t" + " 姓名");  </span></li>
<li><span>System.out.println("-----------------");  </span></li>
<li>
<span>String </span><span>name</span><span> = </span><span>null</span><span>;  </span>
</li>
<li><span>while(rs.next()) {  </span></li>
</ol>

选择sname这列数据

name = rs.getString("sname");

// 首先使用ISO-8859-1字符集将name解码为字节序列并将结果存储新的字节数组中。

// 然后使用GB2312字符集解码指定的字节数组

name = new String(name.getBytes("ISO-8859-1"),"GB2312");

// 输出结果

<ol>
<li><span><span>System.out.println(rs.getString("sno") + "\t" + name);  </span></span></li>
<li><span>}  </span></li>
<li><span>rs.close();  </span></li>
<li><span>conn.close();   </span></li>
<li><span>} catch(ClassNotFoundException e) {   </span></li>
<li><span>System.out.println("Sorry,can`t find the Driver!");   </span></li>
<li><span>e.printStackTrace();   </span></li>
<li><span>} catch(SQLException e) {   </span></li>
<li><span>e.printStackTrace();   </span></li>
<li><span>} catch(Exception e) {   </span></li>
<li><span>e.printStackTrace();   </span></li>
<li><span>}   </span></li>
<li><span>}   </span></li>
<li><span>}  </span></li>
</ol>

接下来我们运行一下看下效果:

D:\testjdbc>javac JDBCTest.java

D:\testjdbc>java JDBCTest

Succeeded connecting to the Database!

-----------------------

执行结果如下所示:

-----------------------

学号 姓名

-----------------------

0104421 周远行

0208123 王义平

0209120 王大力

0309119 李 维

0309203 欧阳美林

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What Are the Limitations of Using Views in MySQL?What Are the Limitations of Using Views in MySQL?May 14, 2025 am 12:10 AM

MySQLviewshavelimitations:1)Theydon'tsupportallSQLoperations,restrictingdatamanipulationthroughviewswithjoinsorsubqueries.2)Theycanimpactperformance,especiallywithcomplexqueriesorlargedatasets.3)Viewsdon'tstoredata,potentiallyleadingtooutdatedinforma

Securing Your MySQL Database: Adding Users and Granting PrivilegesSecuring Your MySQL Database: Adding Users and Granting PrivilegesMay 14, 2025 am 12:09 AM

ProperusermanagementinMySQLiscrucialforenhancingsecurityandensuringefficientdatabaseoperation.1)UseCREATEUSERtoaddusers,specifyingconnectionsourcewith@'localhost'or@'%'.2)GrantspecificprivilegeswithGRANT,usingleastprivilegeprincipletominimizerisks.3)

What Factors Influence the Number of Triggers I Can Use in MySQL?What Factors Influence the Number of Triggers I Can Use in MySQL?May 14, 2025 am 12:08 AM

MySQLdoesn'timposeahardlimitontriggers,butpracticalfactorsdeterminetheireffectiveuse:1)Serverconfigurationimpactstriggermanagement;2)Complextriggersincreasesystemload;3)Largertablesslowtriggerperformance;4)Highconcurrencycancausetriggercontention;5)M

MySQL: Is it safe to store BLOB?MySQL: Is it safe to store BLOB?May 14, 2025 am 12:07 AM

Yes,it'ssafetostoreBLOBdatainMySQL,butconsiderthesefactors:1)StorageSpace:BLOBscanconsumesignificantspace,potentiallyincreasingcostsandslowingperformance.2)Performance:LargerrowsizesduetoBLOBsmayslowdownqueries.3)BackupandRecovery:Theseprocessescanbe

MySQL: Adding a user through a PHP web interfaceMySQL: Adding a user through a PHP web interfaceMay 14, 2025 am 12:04 AM

Adding MySQL users through the PHP web interface can use MySQLi extensions. The steps are as follows: 1. Connect to the MySQL database and use the MySQLi extension. 2. Create a user, use the CREATEUSER statement, and use the PASSWORD() function to encrypt the password. 3. Prevent SQL injection and use the mysqli_real_escape_string() function to process user input. 4. Assign permissions to new users and use the GRANT statement.

MySQL: BLOB and other no-sql storage, what are the differences?MySQL: BLOB and other no-sql storage, what are the differences?May 13, 2025 am 12:14 AM

MySQL'sBLOBissuitableforstoringbinarydatawithinarelationaldatabase,whileNoSQLoptionslikeMongoDB,Redis,andCassandraofferflexible,scalablesolutionsforunstructureddata.BLOBissimplerbutcanslowdownperformancewithlargedata;NoSQLprovidesbetterscalabilityand

MySQL Add User: Syntax, Options, and Security Best PracticesMySQL Add User: Syntax, Options, and Security Best PracticesMay 13, 2025 am 12:12 AM

ToaddauserinMySQL,use:CREATEUSER'username'@'host'IDENTIFIEDBY'password';Here'showtodoitsecurely:1)Choosethehostcarefullytocontrolaccess.2)SetresourcelimitswithoptionslikeMAX_QUERIES_PER_HOUR.3)Usestrong,uniquepasswords.4)EnforceSSL/TLSconnectionswith

MySQL: How to avoid String Data Types common mistakes?MySQL: How to avoid String Data Types common mistakes?May 13, 2025 am 12:09 AM

ToavoidcommonmistakeswithstringdatatypesinMySQL,understandstringtypenuances,choosetherighttype,andmanageencodingandcollationsettingseffectively.1)UseCHARforfixed-lengthstrings,VARCHARforvariable-length,andTEXT/BLOBforlargerdata.2)Setcorrectcharacters

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor