まず、すべてのアプリケーションにweb.config
またはapp.config
のいずれかが含まれています。 MVCアプリケーションまたはWebフォームアプリケーションを作成する場合は、web.config
ファイルがあります。 WindowsサービスまたはWindowsコンソールまたはデスクトップアプリケーションを作成する場合は、代わりにapp.config
ファイルが必要です。
SQL Serverに接続するのはかなり簡単な作業です。 SqlConnectionを使用して接続を作成するだけです。次に、SqlCommandを作成します。最後に、SQLクエリを実行することができます。最初の例あなたは何もデータを返さないクエリを実行している場合
public void DeleteRow()
{
using (var connection = new SqlConnection("your connection string here..."))
{
using (var command = new SqlCommand())
{
command.Connection = connection;
// Next command is your query.
command.CommandText = "DELETE FROM Customers WHERE CustomerId = 1";
command.CommandType = CommandType.Text;
connection.Open();
command.ExecuteNonQuery();
}
}
}
使用:ここで
は一例です。あなたはデータを返すために必要がある場合は、次のように例を使用します。
public void GetCustomer()
{
using (var connection = new SqlConnection("your connection string here..."))
{
using (var command = new SqlCommand())
{
SqlDataReader reader;
command.Connection = connection;
// Next command is your query.
command.CommandText = "SELECT * FROM Customers WHERE CustomerId = 1";
command.CommandType = CommandType.Text;
connection.Open();
reader = cmd.ExecuteReader();
// Data is accessible through the DataReader object here.
}
}
}
一切web.configファイルはありませんが、app.configを –
@PaulAbbottああがあります。うん、私は気付いたが、接続文字列がapp.configに入ることは知らなかった。これはかなり新しいです。 –
はい。 app.configはほとんど同じことです。 –