C#console app issue - 使用多个sql命令的sqlconnection超时

时间:2014-07-01 16:37:34

标签: c# sql sqlconnection sqlcommand

我的控制台应用程序的目标是从server1.database1读取table1,如果目标服务器/数据库/表中不存在该记录,则复制到不同服务器中的同一个表和数据库。

static void Main() {
    try {
        SqlConnection source = new SqlConnection(" blah blah ");
        SqlConnection dest = new SqlConnection(" blah blah ");
        source.Open();
        dest.Open();

        // reads from destination table to make sure data doesn't already exist
        SqlCommand read1 = new SqlCommand(" select string... ", dest);
        object a = read1.ExecuteScalar();
        if (!a.Equals(DBNull.Value)) {
            Console.WriteLine("A record already exists. Press 1 to overwrite:");
            string ans = Console.ReadLine();
            if (ans == "1") {
                // delete row from table if exists
                SqlCommand delete1 = new SqlCommand("DELETE statement...", dest);
                delete1.ExecuteNonQuery();
            }
            else {
                // exit console app
                System.Environment.Exit(1);
            }
        }
        else {
            // reads and copies data from one server to the other
            copyData(selectStr, source, dest, table1, id);
        }
        // Close connections
        connDEV.Close();
        connPROD.Close();
    }
    catch (Exception err) {
        Console.WriteLine(err.ToString());
        Console.ReadKey();
    }
}

// Using SQLbulkcopy and SQLDataReader to copy data
static void copyData(string sqlstr, SqlConnection source, SqlConnection dest, string tableName, string fid) {
    SqlCommand cmd = new SqlCommand(sqlstr, source);
    using (SqlDataReader reader = cmd.ExecuteReader()) {
        int count = reader.FieldCount;
        //////////////////////////////////////////////
        // Copies data from from server to another  //
        //////////////////////////////////////////////
        using (SqlBulkCopy bulkCopy1 = new SqlBulkCopy(dest)) {
            bulkCopy1.DestinationTableName = tableName;
            try {
                bulkCopy1.WriteToServer(reader);
            }
            catch (Exception err) {
                Console.WriteLine(err.Message);
                Console.ReadKey();
            }
        }
        reader.Close();
    }
}

然而,当我执行此代码时,它似乎在第12行超时,即object a = read1.ExecuteScalar();行。错误说:

system.data.sqlclient.sqlexception (0x80131904: timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. ---> system.componentModel.win32exception (8x80004005): the wait operation timed out...

read1只是一个简单的select语句,当我在SQL管理工作室中运行语句时,它查询得很好!

有什么想法吗?

0 个答案:

没有答案