1

I'm trying to teach myself c#, and have found various examples on connecting to a MSSQL database. What I've done seems to be the simplest way to do it, but still seems overly complicated.

Is there a better way?

here's my code:

static void dbcon()
{
    List<int> familyID = new List<int>();
    String connString = "Server=[myServer]\\[myInstance];Database=[dbName];User Id=[userID};Password=[password];";
    using (var sqlconn = new SqlConnection(connString))
    {
        using (var cmd = sqlconn.CreateCommand())
        {
            try
            {
                sqlconn.Open();
                cmd.CommandText = "SELECT id FROM family";
                using (var reader = cmd.ExecuteReader())
                {

                    while (reader.Read())
                    {
                        familyID.Add(Convert.ToInt32(reader["id"].ToString()));
                    }
                }
                foreach (int tempy in familyID)
                {
                    Console.WriteLine("id: " + tempy);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }                   
        }
    }
}
4

3 に答える 3

2

これは、1つのSQLステートメントのみを実行するアプリには問題ありませんが、新しいデータが必要になるたびにそのすべてのコードを使用する必要はありません。

あなたがしたいのは、接続を作成するコードから、SQLを取得して実行するコードから、結果を処理するコードから分離することです。

このように、接続コード(および場合によってはデータ表示コード)を一度記述して、異なるSQLを実行するたびに呼び出すことができ、必要なデータを取得するコードの記述方法に集中するだけで済みます。

hth

于 2012-11-20T05:22:55.773 に答える
0

SqlConnectionStringBuilderのドキュメントに含まれている例は、別の方法として非常に簡単に理解できます。

System.Data.SqlClient.SqlConnectionStringBuilder builder =
  new System.Data.SqlClient.SqlConnectionStringBuilder();
builder["Data Source"] = "(local)";
builder["integrated Security"] = true;
builder["Initial Catalog"] = "AdventureWorks;NewValue=Bad";
Console.WriteLine(builder.ConnectionString);

編集:

実際、上でコピーした例は、SqlConnectionStringBuilder クラスが「...無効な値を安全な方法で」処理する方法を示しています。おっと。少なくとも、それがどのように機能するかについてのアイデアを提供します。

ADO.NET 内で接続文字列を取得、保存、および構築するさまざまな方法の詳細については、接続文字列に関する MSDN ドキュメントを参照してください。

于 2012-11-20T07:41:52.453 に答える
0

詳細:まず、Stackoverflow へようこそ。以下にいくつかのヒントを示します

接続文字列をそのようにハードコーディングするのは悪い習慣です。常に App.config (または Web アプリケーションの場合は Web.config) に含める必要があります。その理由は、ハード コードした場合、上司からアプリケーション データベースの接続文字列を変更するように求められた場合、アプリケーション全体を再コンパイルする必要があるからです。App.config ファイルにある場合は、変更 (メモ帳で開く) して保存するだけです。

app.config に追加する方法の例

<configuration>
   <connectionStrings>
         <add name="myConnectionString" 
           connectionString="Data Source=localhost;Initial Catalog=MySQLServerDB; 
           Integrated Security=true" providerName="System.Data.SqlClient" />
   </connectionStrings>
</configuration>

次に、コードでアクセスします (System.Configuration への参照を追加するだけでなく、System.Configuration を使用して追加する必要があります)。

string connString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;

他のコードに関しては、例外のキャッチを変更して、最初に Sql Exception を含めてから、他の例外にフォールバックします。

  catch (SqlException ex)
  {
      // Handle the Sql Exception code
  }
  catch (Exception ex)
  {
      // Handle the Normal Exception code
  }
于 2012-11-20T06:49:36.423 に答える