赞
踩
1、添加依赖:
2、demo:
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.SQLException;
-
- public class SQLServerJdbcDemo {
- public static void main(String[] args) {
- // 定义连接字符串,格式为:jdbc:sqlserver://服务器地址:端口号;databaseName=数据库名
- String connectionString = "jdbc:sqlserver://localhost:1433;databaseName=你的数据库名";
- // 定义SQL Server的用户和密码
- String username = "你的用户名";
- String password = "你的密码";
-
- try {
- // 加载SQL Server JDBC驱动
- Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
- // 建立连接
- Connection connection = DriverManager.getConnection(connectionString, username, password);
- System.out.println("连接成功!");
- // 这里可以执行SQL语句等操作
- String sql = "SELECT * FROM table_name";
- statement = con.prepareStatement(sql);
- ResultSet resultSet = statement.executeQuery();
- while (resultSet.next()) {
- //遍历数据
- }
- statement.close();
- // 关闭连接
- connection.close();
- } catch (ClassNotFoundException e) {
- System.out.println("JDBC驱动未找到!");
- } catch (SQLException e) {
- System.out.println("数据库连接失败!或者SQL异常!");
- }
- }
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。