kTrace() ;
}
}
if(stmt != null){ // 关闭声明
try{
stmt.close() ;
}catch(SQLException e){
e.printStackTrace() ;
}
}
if(conn != null){ // 关闭连接对象
try{
conn.close() ;
}catch(SQLException e){
e.printStackTrace() ;
}
}
?
上面那段文字介绍的挺好的,还有我自己也是初学,就直接转载了,在此表示感谢!下面贴上我的一段入门级代码,要毕业了,马上要工作了,想多接触一点工作上可能用得到的JDBC数据库开发,有没有时间写个很大的项目,所以就只是描述一下大致流程,见笑了!
?
import java.sql.*;
public class JDBCDemo {
public static void main(String[] args) {
String user = "root";
String password = "199203211410xfcy";
String url = "jdbc:mysql://localhost:3306/studentdb";//建立数据库服务器的地址
String tableName = "student_information";
String driver = "com.mysql.jdbc.Driver";
String sqlSentence;
Connection con = null;//连接对象
Statement stmt = null;//操作对象
ResultSet rs = null;//查询结果
try {
Class.forName(driver);//加载数据库驱动程序Driver类
con = DriverManager.getConnection(url, user, password);//数据库连接,以特定的用户访问指定的数据库
stmt = con.createStatement();
sqlSentence = "insert into " + tableName + " values (9,'honey',21)";
stmt.executeUpdate(sqlSentence);
sqlSentence = "select * from " + tableName;
rs = stmt.executeQuery(sqlSentence);
ResultSetMetaData rsmd = rs.getMetaData();
int j = 0;
j = rsmd.getColumnCount();
for (int k = 0; k < j; k++) {
System.out.print(rsmd.getColumnName(k + 1));
System.out.print("\t");
}
System.out.println();
while (rs.next()) {
for (int i = 0; i < j; i++) {
System.out.print(rs.getString(i + 1));
System.out.print("\t");
}
System.out.println();
}
} catch (ClassNotFoundException e1) {
System.out.println("数据库驱动不存在!");
System.out.println(e1.toString());
} catch (SQLException e2) {
System.out.println("数据库存在异常!");
System.out.println(e2.toString());
} finally {
try {
if (rs != null)
rs.close();
if (stmt != null)
stmt.close();
if (con != null)
con.close();
} catch (SQLException e) {
System.out.println(e.toString());
}
}
}
}
前提是要有一个studentdb的数据库,和一张属性一致的student_information表。
?
?
由于时间有限,在写博文的过程中参考过一些文献,在此表示感谢;同时鉴于水平原因,你难免有不足之处,欢迎斧正!
?
?
?
?
?
?