MsSql java连接

问题描述 投票:0回答:2

我收到这个错误你能帮我吗

结果:与主机 127.0.0.1 的连接,命名实例 sqlexpress 失败。错误:“java.net.SocketTimeoutException:接收超时”。验证服务器和实例名称,并检查没有防火墙阻止到端口 1434 的 UDP 流量。对于 SQL Server 2005 或更高版本,验证 SQL Server 浏览器服务是否正在主机上运行。

package deneme;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class deneme {

    public static void main(String[] args) {
        
        // Bağlantı parametrelerini belirleyin
        String serverName = "localhost\\SQLEXPRESS";
        String databaseName = "TestDatabase";
        
        // Windows Authentication kullanarak SQL Server'a bağlanın
        String url = "jdbc:sqlserver://" + serverName +
                     ";databaseName=" + databaseName + ";integratedSecurity=true;";
        Connection conn = null;
        Statement stmt = null;
        try {
            conn = DriverManager.getConnection(url);
            System.out.println("Bağlantı başarılı.");
            
            // Tablo oluşturma sorgusunu yazın
            String createTableQuery = "CREATE TABLE Products " +
                                      "(ID INT PRIMARY KEY NOT NULL, " +
                                      " NAME TEXT NOT NULL, " +
                                      " PRICE REAL NOT NULL)";
            
            // Sorguyu çalıştırın
            stmt = conn.createStatement();
            stmt.executeUpdate(createTableQuery);
            System.out.println("Tablo başarıyla oluşturuldu.");
            
        } catch (SQLException e) {
            System.out.println("Bağlantı hatası: " + e.getMessage());
        } finally {
            // Kaynakları serbest bırakın
            try {
                if (stmt != null)
                    stmt.close();
                if (conn != null)
                    conn.close();
            } catch (SQLException e) {
                System.out.println("Kaynakları serbest bırakırken hata oluştu: " + e.getMessage());
            }
        }
    }
}
java sql sql-server sql-server-ce mssql-jdbc
2个回答
0
投票

将实例名称与服务器名称分开应该可以解决您的问题。尝试以下连接字符串:

String serverName = "localhost:1434";
String instanceName = "SQLEXPRESS";
String databaseName = "TestDatabase";
String url = "jdbc:sqlserver://" + serverName + ";instanceName=" + instanceName + ";databaseName=" + databaseName + ";integratedSecurity=true;";

查看此处了解更多信息。


0
投票

查看此链接以检查提供的答案,它与您面临的问题有关:

https://stackoverflow.com/a/12524566/21523351

© www.soinside.com 2019 - 2024. All rights reserved.