设为首页 加入收藏

TOP

JDBC数据库编程(二)
2015-07-24 10:46:18 来源: 作者: 【 】 浏览:4
Tags:JDBC 数据库 编程
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表。

?

?

由于时间有限,在写博文的过程中参考过一些文献,在此表示感谢;同时鉴于水平原因,你难免有不足之处,欢迎斧正!

?

?

?

?

?

?

首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇将数据库中的数字显示为文字 下一篇第十一章数据库管理类的实现

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·Asus Armoury Crate (2025-12-26 02:52:33)
·WindowsFX (LinuxFX) (2025-12-26 02:52:30)
·[ Linux运维学习 ] (2025-12-26 02:52:27)
·HTTPS 详解一:附带 (2025-12-26 02:20:37)
·TCP/IP协议到底在讲 (2025-12-26 02:20:34)