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
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

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1
Powerful PHP integrated development environment