Java连接SQLServer2012数据库

本文介绍了一个使用Java进行SQLServer数据库连接及查询的基本示例。通过该示例,读者可以了解到如何加载数据库驱动、建立连接、执行SQL查询并处理结果集。此示例还展示了如何遍历查询结果并打印相关信息。

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

import java.sql.*;

public class Demo {

	public static void main(String[] args) {

		//声明变量
		Connection con = null;
		Statement sta = null;
		ResultSet res = null;

		try {
			//数据库地址
			String url = "jdbc:sqlserver://localhost:1433;databaseName=数据库名;";
			//用户名,密码
			String user = "sa";
			String password = "1234";
			//装载Class
			Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
			//连接数据库
			con = DriverManager.getConnection(url, user, password);
			sta = con.createStatement();
			//执行SQL语句
			String sql = "SELECT * FROM Table";
			res = sta.executeQuery(sql);
			//
			while(res.next()){
				System.out.println(res.getString("Name")+"   "+res.getInt("Age")+"   "+res.getString("Sex"));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			//关闭数据库连接
			if(res != null){
				res.close();
			}
			if(sta != null){
				sta.close();
			}
			if(con != null){
				con.close();
			}
		}
		
	}

}

使用sqljdbc4.jar

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值