如何在C#中以编程方式连接到SQL Server?

时间:2023-01-19 23:11:38

I have developed a program (C#) which creates a SQL database using this code:

我开发了一个程序(C#),它使用以下代码创建一个SQL数据库:

string SQLCreation = "IF NOT EXISTS (SELECT * FROM master..sysdatabases WHERE Name = 'x') CREATE DATABASE x";
SqlConnection PublicSQLDBCreationConnection = new SqlConnection(connectionString);
SqlCommand PublicSQLDBCreation = new SqlCommand(SQLCreation, PublicSQLDBCreationConnection);

try
{
   PublicSQLDBCreationConnection.Open();
   PublicSQLDBCreation.ExecuteNonQuery();
   PublicSQLDBCreationConnection.Close();
}
//'then creates a table and so on

Now I want to have a client application which connects to this database (via LAN) WITHOUT using IP or computer name. How is that possible? Is it possible do this and have a dataset while not mentioning IP Adr. or computer name?

现在我希望有一个客户端应用程序连接到这个数据库(通过LAN)而不使用IP或计算机名称。怎么可能?是否可以这样做,并有一个数据集,而没有提到IP Adr。还是电脑名?


P.S. Don't Worry Guys, I simplified my code just for your view, I have made sure that SQL injection or other attempts won't happen. Also I have to say that My Reason for not mentioning servername or IP is that I want to mass deploy my Application on many Networks

附:不要担心伙伴,我简化了我的代码只是为了你的观点,我已经确保SQL注入或其他尝试不会发生。另外我不得不说,我没有提到服务器名称或IP的原因是我想在许多网络上大规模部署我的应用程序

1 个解决方案

#1


1  

You could use SqlDataSourceEnumerator to get a list of all Sql Servers that are visible and browsable. This is not a good technique, since you could get an instance that you don't have the right to create a database on it, but you could still try something with that.

您可以使用SqlDataSourceEnumerator获取可见且可浏览的所有Sql Server的列表。这不是一个好的技术,因为你可以获得一个你无权在其上创建数据库的实例,但你仍然可以尝试使用它。

var enumerator = SqlDataSourceEnumerator.Instance;
foreach (DataRow row in enumerator.GetDataSources().Rows)
{
    var serverName = row["ServerName"];
    var instance = row["InstanceName"];

    // build a connection string and try to connect to it
}

#1


1  

You could use SqlDataSourceEnumerator to get a list of all Sql Servers that are visible and browsable. This is not a good technique, since you could get an instance that you don't have the right to create a database on it, but you could still try something with that.

您可以使用SqlDataSourceEnumerator获取可见且可浏览的所有Sql Server的列表。这不是一个好的技术,因为你可以获得一个你无权在其上创建数据库的实例,但你仍然可以尝试使用它。

var enumerator = SqlDataSourceEnumerator.Instance;
foreach (DataRow row in enumerator.GetDataSources().Rows)
{
    var serverName = row["ServerName"];
    var instance = row["InstanceName"];

    // build a connection string and try to connect to it
}