简单介绍一个java连接数据库,和数据库交互的过程。
首先我们先看下是怎么和数据库交互的:如下图所示:
java程序通过jdbc驱动来连接数据库,成功连接数据库后,可以对数据库中的数据进行进本的curd的操作,如何连接数据库呢?先讲下几个简单的定义:
class.forName:用于加载驱动,其中连接不同类型的数据库驱动是不一样的,具体的会在下面讲解,其中在加载驱动的后面有个newInstance()的方法,此方法是用于分配产生一个新的对象。
DriverManager:用于管理JDBC驱动的服务类,主要方法是获得Connection对象
ConnectIon:用于连接指定的数据库,其中connection有三个参数,一个是数据库所在的路径,一个是数据库的用户名,一个是数据库的密码
preparedStatement:通过数据库连接后得到要执行的语句
resultSet:要处理的结果集,用户数据库的查询操作。
示例:传统JDBC访问数据库步骤
通过Class.forName(String driverClass)注册数据库驱动
通过DriverManager.getConnection(Stringurl,String user,String password)获得数据库连接对象
通过Connnection.createStatement()或者Connection.createPreparedStatement(String sql)创建相应的Statement对象或者通过PreparedStatement preparedStatement=connection.prepareStatement(sqlString)创建对象;
通过Statement.execute(String sql)或者PreparedStatement.execute()执行相应的SQL,并返回ResultSet对象
操作ResultSet
一般来说对于增加,删除,修改,执行的是executeUpdate()方法,而对于查询得到的是executeQuery(),对于前者我们用影响的行数来判断是否成功,而后者因为进行查询操作没有对数据库的行数有变化,我们用resultset.next()来逐行遍历
我们看一个例子:
try{
Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
String url="jdbc:jtds:sqlServer://localhost:1433/hsDemo";
String pwd="sa";
String user="sa";
Connection connection=DriverManager.getConnection(url,user,pwd);
if(connection!=null){
System.out.println("you success to connect the database!");
}
else{
System.out.println("fail to connect the database!");
}
判断数据库是否连接成功,当对数据库连接成功后我们可以进行对数据库的交互
进行查询的操作的时候如下:
String sqlString="select * from demo";
PreparedStatement preparedStatement=connection.prepareStatement(sqlString);
resultSet=preparedStatement.executeQuery();
while(resultSet.next()){
System.out.println("name"+"\t"+"pwd");
System.out.println(resultSet.getString(2)+"\t"+resultSet.getString(3));
}
其中resultset指向的是当前查询的是前一行数据,然后用get方法得到我们要查询的数据
当我们想进行的是删除操作的时候,代码如下:
String sqlString="delete from demo where id=1";
PreparedStatement preparedStatement=connection.prepareStatement(sqlString);
int c=preparedStatement.executeUpdate();
if (c!=0) {
System.out.print("success to delete!");
}else{
System.out.println("fail to delete");
}
对于增加和修改的操作也是一样。
下面我们来看下java连接不同的数据库的操作:
oracle连接数据库:
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
String url="jdbc:oracle:thin:@localhost:1521:orcl";
String user="scott";
String passWord="tiger";
Connection conn= DriverManager.getConnection(url,user,password);
sqlserver连接数据库(jdbc):
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance();
String url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=pubs";
String user="sa";
String password="";
Connection conn= DriverManager.getConnection(url,user,password);
Statement stmt=conn.createStatement();
mysql连接数据库:
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
String url ="jdbc:mysql://localhost/softforum?user=soft&password=soft1234"
Connection conn= DriverManager.getConnection(url);
我们进行了对上述的操作后不要忘了关闭数据库的操作,关闭的操作和前面连接数据库的操作顺序是相反的,比如先是连接成功的数据库,而这里最后进行的是关闭数据库。
下面是通过jdbc来连接mysql数据库并进行相应的CURD的操作代码:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import com.mysql.jdbc.PreparedStatement;
public class MysqlTest {
/**
* @param args
* 传统的jdbc连接数据库并进行相应的操作
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
PreparedStatement pst=null;
ResultSet rs=null;
try {
Class.forName("org.gjt.mm.mysql.Driver").newInstance();
String url ="jdbc:mysql://localhost:3306/gpdidemo?user=root&password=root";
Connection conn= DriverManager.getConnection(url);
/*
* 执行查询的操作
* String sqlString="select * from userinfo";
pst=(PreparedStatement) conn.prepareStatement(sqlString);
rs=pst.executeQuery();
while(rs.next()){
System.out.print(rs.getString(1)+"\t"+rs.getString(2)+"\t"+rs.getString(3));
}
*/
/*
* 执行更更新操作
* pst=(PreparedStatement) conn.prepareStatement("update userinfo set userpwd='pwd' where id=1");
int count=pst.executeUpdate();
if (count==0) {
System.out.println("update execute fail");
}else{
System.out.println("update execute success");
}
if (conn!=null) {
System.out.println("success");
}else{
System.out.println("fail");
}*/
/*
* 添加信息部分
* pst=(PreparedStatement) conn.prepareStatement("insert into userinfo(username,userpwd) values(?,?);");
pst.setString(1, "gao");
pst.setString(2, "gpwd");
pst.execute();
*/
/*
* 根据id删除数据部分
* pst=(PreparedStatement) conn.prepareStatement("delete from userinfo where id=2");
pst.execute();*/
if (conn!=null) {
conn.close();
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
其中表userinfo中总共三个字段