1

我正在尝试将一些 perl 代码翻译成 C#,但我遇到了以下问题。

建立sql server连接并执行select语句后,如何引用表列中的不同元素。例如,在 Perl 中它看起来像:

  my $dbh = DBI -> connect( NAME, USR, PWD )
            or die "Failed to connect to database: " . DBI->message;

  my $dbname = DB_NAME;
  my $dbschema = DB_SCHEMA;
  my $sql = qq{select a,b,c,d,e,f,g,h,i,...
             from $dbname.$dbschema.package p
             join $dbname.$dbschema.package_download pd on p.package_id = pd.package_id
             join $dbname.$dbschema.download d on pd.download_id = d.download_id
            where p.package_name = '$package'
              --and ds.server_address like 'tcp/ip'
            order by a,b,c,d,..};

  my $sth = $dbh -> prepare( $sql )
   or die "Failed to prepare statement: " . $dbh->message;

  $sth -> execute()
   or die "Failed to execute statement: " . $sth->message;

  #now to go through each row in result table

  while ( @data = $sth->fetchrow_array() )
  { 
    print "$data[0]";
    # If source server FTP is not already open, make new FTP
    if ( $data[0] != $src_id )
    {
        if ( $src_ftp )
        { $src_ftp -> quit; }
        $src_ftp = make_ftp( $data[1], $data[2], $data[3], $data[18], $data[19], $data[20] );
        $src_id = $data[0];
    } 
  }

到目前为止,我已经把它归结为

string db =  NAME;
        string myConnectionString = "Data Source=ServerName;" + "Initial Catalog=" + db + "User id=" + ODBC_USR + "Password=" + PWD
        SqlConnection myConnection = new SqlConnection(myConnectionString);

     string myInsertQuery = "select a,b,c,d,e,f,g,h,i,...
             from $dbname.$dbschema.package p
             join $dbname.$dbschema.package_download pd on p.package_id = pd.package_id
             join $dbname.$dbschema.download d on pd.download_id = d.download_id
            where p.package_name = '$package'
              --and ds.server_address like 'tcp/ip'
            order by a,b,c,d,..";

     SqlCommand myCommand = new SqlCommand(myInsertQuery);
        myCommand.Connection = myConnection;
        myConnection.Open();
        myCommand.ExecuteNonQuery();
        myCommand.Connection.Close();

但是如何在 C# 中引用 data[0] 和 data[1] 之类的列。抱歉,我对这两种语言都不熟悉,所以我的背景严重不足。谢谢!

4

2 回答 2

2

您可以通过列名数字顺序(它以 0 作为第一列开头)直接引用您的列,或者通过 、DataTable或特定的。作为示例,我将在这里使用 DataTable,并将其命名为,假设我们要引用第一行,那么您可以使用以下语法/格式来引用它:DataSetDataReaderDataRowdt

dt[RowNumber]["ColumnName or Column Number"].ToString();

例如:

dt[0]["a"].ToString();

或按编号为 0 的第一列,例如:

dt[0][0].ToString();

顺便使用Parameters一下,因为没有它,它很容易受到SQL Injection的影响。下面是更完整的代码:

 string db =  NAME;
 string myConnectionString = "Data Source=ServerName;" + "Initial Catalog=" + db + "User id=" + ODBC_USR + "Password=" + PWD

 using (SqlConnection connection = new SqlConnection(myConnectionString))
    {
      string mySelectQuery = @"SELECT a,b,c,d,e,f,g,h,i,...
         FROM package p
         JOIN package_download pd on p.package_id = pd.package_id
         join download d on pd.download_id = d.download_id
        WHERE p.package_name = @PackageName
        AND ds.server_address LIKE 'tcp/ip%'
        ORDER by a,b,c,d";

        try
        {
            connection.Open();
            using (SqlDataAdapter da = new SqlDataAdapter(mySelectQuery, connection))
            {

                using (SqlCommand cmd = new SqlCommand())
                {
                    da.SelectCommand.Parameters.AddWithValue("@PackageName", txtPackage.Text);

                        DataTable dt = new DataTable();
                        da.Fill(dt);         
                        if (dt.Rows.Count>0) // Make sure there is something in your DataTable
                         {
                           String aVal = dt[0]["a"].ToString();
                           String bVal = dt[0]["b"].ToString();
                           // You'll be the one to fill up
                         }                                                          
                }
            }

        }
        catch (Exception ex)
        {
          MessageBox.Show(ex.Message);
        }

    }

我将您更改LIKE 'tcp/ip'LIKE 'tcp/ip%'使用更合适的方式LIKE

于 2013-07-27T04:39:38.557 回答
0

您可以使用 ado.net 实体数据表来引用 sql server 中的表。我不知道你是不是在问这个,但它可能会有所帮助。因为据我所知,直接引用 sql server 是不可能的。

于 2013-07-27T03:54:40.297 回答