MyEclipse使用Java 通过JDBC连接MySQL数据库的基本测试_MySQL
bitsCN.com
MyEclipse使用Java 通过JDBC连接MySQL数据库的基本测试
1.前提是MyEclipse已经能正常开发Java工程。
2.安装MySQL
个人使用的是版本是 mysql-5.0.22-win32.zip
网址:http://www.mysql.com/downloads/mysql/#downloads
3.下载JDBC驱动
个人使用的是 mysql-connector-java-5.1.22.zip,所需要的就是解压缩之后其中的 mysql-connector-java-5.1.22-bin.jar
网址:http://www.mysql.com/downloads/connector/j/
4.代码测试
1 package ts.jsj.lyh; 2 3 import java.sql.*; 4 5 /** *//** 6 * 使用JDBC连接数据库MySQL的过程 7 * DataBase:JSJ, table:student; 8 * @author DuChangfeng 2008 09 18 9 */10 public class JDBCTest {11 12 public static Connection getConnection() throws SQLException, 13 java.lang.ClassNotFoundException 14 {15 //第一步:加载MySQL的JDBC的驱动16 Class.forName("com.mysql.jdbc.Driver");17 18 //取得连接的url,能访问MySQL数据库的用户名,密码;jsj:数据库名19 String url = "jdbc:mysql://localhost:3306/jsj"; 20 String username = "root";21 String password = "111";22 23 //第二步:创建与MySQL数据库的连接类的实例24 Connection con = DriverManager.getConnection(url, username, password); 25 return con; 26 }27 28 29 public static void main(String args[]) {30 try31 {32 //第三步:获取连接类实例con,用con创建Statement对象类实例 sql_statement33 Connection con = getConnection(); 34 Statement sql_statement = con.createStatement();35 36 /** *//************ 对数据库进行相关操作 ************/ 37 //如果同名数据库存在,删除38 //sql_statement.executeUpdate("drop table if exists student"); 39 //执行了一个sql语句生成了一个名为student的表40 //sql_statement.executeUpdate("create table student (id int not null auto_increment, name varchar(20) not null default 'name', math int not null default 60, primary key (id) ); ");41 //向表中插入数据42 //sql_statement.executeUpdate("insert student values(1, 'liying', 98)");43 //sql_statement.executeUpdate("insert student values(2, 'jiangshan', 88)");44 //sql_statement.executeUpdate("insert student values(3, 'wangjiawu', 78)");45 //sql_statement.executeUpdate("insert student values(4, 'duchangfeng', 100)");46 //---以上操作不实用,但是列出来作为参考---47 48 //第四步:执行查询,用ResultSet类的对象,返回查询的结果49 String query = "select * from student"; 50 ResultSet result = sql_statement.executeQuery(query);51 /** *//************ 对数据库进行相关操作 ************/52 53 System.out.println("Student表中的数据如下:");54 System.out.println("------------------------");55 System.out.println("学号" + " " + "姓名" + " " + "数据成绩 ");56 System.out.println("------------------------");57 58 //对获得的查询结果进行处理,对Result类的对象进行操作59 while (result.next()) 60 {61 int number = result.getInt("sno");62 String name = result.getString("sname");63 String mathScore = result.getString("sgrade");64 //取得数据库中的数据65 System.out.println(" " + number + " " + name + " " + mathScore); 66 }67 68 //关闭连接和声明69 sql_statement.close();70 con.close();71 72 } catch(java.lang.ClassNotFoundException e) {73 //加载JDBC错误,所要用的驱动没有找到74 System.err.print("ClassNotFoundException");75 //其他错误76 System.err.println(e.getMessage());77 } catch (SQLException ex) {78 //显示数据库连接错误或查询错误79 System.err.println("SQLException: " + ex.getMessage());80 }81 }82 83 }
以上大部分内容整理自网络,感谢猿猿们的无私奉献~~具体的步骤、强大的互联网上都比较容易查询的到,这里不再赘述,现加上几点个人认为需要注意的地方:
1) 关于mysql-connector-java-5.1.22-bin.jar 的存放位置。在MyEclipse具体的java工程中新建一存放jar 包的文件夹(如 lib),将mysql-connector-java-5.1.22-bin.jar 复制到文件夹中,选中jar包右击--->Build Path--->Add To Build Path,即可。
若出现
ClassNotFoundExceptioncom.mysql.jdbc.Driver
的提示,则正是由于缺少导入jar包所造成的。
2) 如果已经对MySQL的使用很熟悉,则可忽略这条。个人在测试连接时,老是出现这样的异常提示:
SQLException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
这正是由于个人对MySQL使用不熟悉,对MySQL进行了诸多尝试性的操作,不知何时无意中将MySQL的服务(如果在安装MySQL时没有更改的话,缺省服务名就是MySQL)关闭,解决方法开启此服务即可。控制面板--->管理工具--->服务--->MySQL--->选择启用。
3)在使用上面的代码测试时,需要更改的地方有:
//MySQL数据库的用户名,密码,数据库名
19 String url = "jdbc:mysql://localhost:3306/jsj";
20 String username = "root";
21 String password = "111";
以及具体基本表中的所要查询的字段名:
61 int number = result.getInt("sno");
62 String name = result.getString("sname");
63 String mathScore = result.getString("sgrade");
多多分享,有问题欢迎交流~~
bitsCN.com
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



Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Guide to Random Number Generator in Java. Here we discuss Functions in Java with examples and two different Generators with ther examples.

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4
