Java学习笔记――JDBC之与数据库MySQL的连接以及增删改查等操作 (一)

2014-11-24 10:11:48 · 作者: · 浏览: 3

必须的准备工作
一、MySQL的安装。
二、下载 jdbc 驱动。可以从在官网上下载,
三、在 Eclipse 的 Java 工程中新建一个 lib 文件夹,将所准备的 JAR 包复制进去。
四、右键该 JAR 包:Build Path --> Add to Build Path


连接的理论知识
需要用到 Java.sql.*; 中的几个相关类:
Connection类
负责建立与指定URL(包含数据库IP地址、库名、用户名和密码的信息)的连接;
Connection conn = DriverManager.getConnection(url,user,password);


DriverManager.getConnection(url);
利用驱动管理器类获取指定URL连接
[java]
String url = "jdbc:mysql://localhost:3306/test"; //连接URL为 jdbc:mysql//服务器地址/数据库

String url = "jdbc:mysql://localhost:3306/test"; //连接URL为 jdbc:mysql//服务器地址/数据库名 Statement类
stmt = conn.createStatment();
语句对象,用来向数据库发送一条SQL语句
rs = stmt.executeQuery(sql) //返回记录集对象,用于查询
int count = stmt.executeUpdate(sql) //执行一条增删改语句,返回int
stmt.execute(sql) //增删改都可以,返回布尔值(执行成功or失败)

ResultSet类
记录集对象,存储executeQuery()方法返回的记录集合。用相关的rs.getString("列名") rs.getInt("列名")等方法获取指定列的值。

连接测试
Java代码如下:
[java]
package com.sql;

import java.sql.*;

public class JDBC0726_Base {
Connection connection;
Statement statement;
ResultSet rSet;
//返回一个与特定数据库的连接
public Connection getConnection() {
try {
//连接URL为 jdbc:mysql//服务器地址/数据库名 ,后面的2个参数分别是登陆用户名和密码
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "yongqiang");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return connection;
}
public static void main(String[] args) {
JDBC0726_Base jDao = new JDBC0726_Base();
System.out.println(jDao.getConnection());
}
}

package com.sql;

import java.sql.*;

public class JDBC0726_Base {
Connection connection;
Statement statement;
ResultSet rSet;
//返回一个与特定数据库的连接
public Connection getConnection() {
try {
//连接URL为 jdbc:mysql//服务器地址/数据库名 ,后面的2个参数分别是登陆用户名和密码
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "yongqiang");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return connection;
}
public static void main(String[] args) {
JDBC0726_Base jDao = new JDBC0726_Base();
System.out.println(jDao.getConnection());
}
}

如果输出相应的对象地址,而不是异常,则证明连接成功。


用 Java 对SQL进行相关操作
【注】以下操作需要依托于上面的 getConnection() 方法
非查询类SQL语句
[java]
//非查询类
public int Update(String sql) {
getConnection();
int count =0;
try {
statement = connection.createStatement();
count = statement.executeUpdate(sql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
try {
if (statement != null) {
statement.close();
statement = null;
}
if (connection != null) {
connection.close();
connection = null;
}
} catch (SQLException e2) {
// TODO: handle exception
}
}
return count;
}

//非查询类
public int Update(String sql) {
getConnection();
int count =0;
try {
statement = connection.createStatement();
count = statement.executeUpdate(sql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
try {
if (statement != null) {
statement.close();
statement = nu