jdbc数据连接

本文介绍了一个简单的Java程序示例,展示了如何通过使用JDBC连接到SQL Server数据库,并执行基本的数据库操作如增删改查。示例中包含了数据库连接配置、执行SQL语句的方法及结果集处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

/** 数据库连接*/
public class BaseDao {
	public final static String quDong = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; // 数据库驱动
	public final static String duanKOu = "jdbc:sqlserver://localhost:1433;databasename = news";// jdbc:sqlservier://数据库IP:端口号;DatabaseName=数据库
	public final static String name = "sa";// 数据库名字
	public final static String miMa = "sa";// 密码
	protected Statement stmt;
	protected ResultSet rs;

/** 关闭所有连接 */
	public void closeAll(ResultSet rs, PreparedStatement pretmt, Connection conn) {
		if (rs != null) {
			try {
				rs.close();
			} catch (Exception e) {
				e.printStackTrace();

			}
		}
		if (pretmt != null) {
			try {
				pretmt.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (conn != null) {
			try {
				conn.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

/**返回数据库连接*/
	public Connection fanHuiShuJuKuLianJie() {
		Connection connetion = null;
		try {
			Class.forName(quDong);
			connetion = DriverManager.getConnection(duanKOu, name, miMa);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return connetion;
	}

/**执行SQL语句,可进行增,删,改*/
	public int ShuJuKuChaoZuo(String Sql, String[] param) {
		Connection con = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		int num = 0;
		try {
			con = fanHuiShuJuKuLianJie();// 得到数据库连接
			pstmt = con.prepareStatement(Sql);
			if (param != null) {
				for (int i = 0; i < param.length; i++) {
					pstmt.setString(i + 1, param[i]);// 设置参数
				}
			}
			num = pstmt.executeUpdate();// 执行SQL语句
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			closeAll(rs, pstmt, con);
		}
		return num;
	}

	public static String getStr(String info) {
		try {
			byte[] b = info.getBytes("ISO-8859-1");
			return new String(b, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return "";
		}

	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值