jdbc操作步骤
- 加载驱动
- 创建连接
- 生成对象
- 对话
- 收尾
代码展示
import java.sql.*;
public class jdbctest1 {
public static void main(String[] args){
//加载驱动
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.err.println("驱动加载失败!");
e.printStackTrace();
}
//创建链接
Connection conn=null;
try {
conn= DriverManager.getConnection("jdbc:mysql://localhost:33060/mytest","root","Root");
} catch (SQLException e) {
System.err.println("连接创建失败!");
e.printStackTrace();
}
//生成对象
Statement stmt=null;
try {
stmt=conn.createStatement();
} catch (SQLException e) {
System.err.println("对象生成失败!");
e.printStackTrace();
}
// 对话
try {
int count =stmt.executeUpdate("update s set sname='cccc' where sno=3");
System.out.println("数据库中发生了"+count+"行变化");
} catch (SQLException e) {
System.err.println("对话失败!");
e.printStackTrace();
}
ResultSet res=null;
try {
res=stmt.executeQuery("select * from s where sage>18");
while(res.next()){
String sno=res.getString(1);
String sname=res.getString(2);
String sclass=res.getString(3);
int sage=res.getInt(4);
System.out.println(sno+"\t"+sname+"\t"+sclass+"\t"+sage);
ResultSetMetaData rsmd=res.getMetaData();
int length=rsmd.getColumnCount();
for(int i=1;i<length;i++){
System.out.print(res.getObject(i)+"\t");
}
System.out.println("");
}
} catch (SQLException e) {
e.printStackTrace();
}
//收尾
if (res!=null){
try {
res.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stmt!=null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
总体步骤跟上一篇文章是差不多的,区别就在于与数据库进行对话时使用的方法,具体区别就不在这里跟大家讲解,可以点击这里进行参考。在这里使用的是executeQuery,因为这个方法返回的是ResultSet,所以就涉及到了上面代码中的几个方法
- res.getString(i):得到数据库表第i栏中的内容
- ResultSetMetaData:获取数据库表元数据
- getColumnCount():得到数据库表共有多少列数据
在最后不要忘记,要关闭资源避免产生脏数据。