MySQL驱动程序添加到eclipse中后,就可以尝试在eclipse中使用数据库了。
1、加载驱动程序
驱动程序地址:com.mysql.jdbc.Driver
用Class类加载驱动程序,如下
package test;
public class TestClass {
public static String Driver="com.mysql.jdbc.Driver"; //数据库驱动软件中地址
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
Class.forName(Driver); //加载驱动程序
System.out.println("success");
}catch(Exception w) {
w.printStackTrace();
System.out.println("****");
}
}
}
输出“success”表示加载成功。
2、连接和关闭数据库
eclipse中提供了DriverManager类连接数据库,通过getConnection()方法取得连接对象,返回一个Connection对象。
getConnection()方法中的参数为MySQL的连接地址、用户名和密码。
MySQL数据库的连接地址格式为
jdbc:mysql://IP地址:端口号/数据库名称
如果是本机中的数据库,IP地址为localhost,端口号为3306。
我的数据库名:root,密码:123456。建立了一个数据库bb,并在其中建表b2,添加数据。查询效果:
之后的操作都基于这个数据库。所以我的连接地址为:jdbc:mysql://localhost:3306/bb
在eclipse中连接和关闭数据库:
package test;
import java.sql.Connection;
import java.sql.DriverManager;
public class StartClass {
public static final String Driver="com.mysql.jdbc.Driver";
public static final String URL="jdbc:mysql://localhost:3306/bb";
//格式 jdbc:mysql://IP地址:端口号/数据库名称
public static void main(String args[]) {
Connection con=null;
try {
Class.forName(Driver);
}catch(Exception e) {
e.printStackTrace();
}
try {
con=DriverManager.getConnection(URL,"root","123456"); //数据库地址,数据库用户名,密码
System.out.println("***");
}catch(Exception e) {
e.printStackTrace();
}
System.out.println(con);
try {
con.close(); //关闭数据库
}catch(Exception e) {
e.printStackTrace();
}
}
}
输出不为空,表示连接成功:
***
com.mysql.jdbc.JDBC4Connection@5910e440
建议用完数据库后删除,避免占用较大资源。
3、数据库更新数据
数据的更新需要用Statement接口完成,通过Connection接口中提供的createStatement实例化。
3.1、数据插入
首先是实例化一个Statement,然后是数据库建表中的数据插入命令,将该命令添加到Statement类的executeUpdate()方法中。
看一个例子: