我有这样的功能
try
{
using(var sConnection = new SqlConnection(ConnectionString))
using(var sCommand = sConnection.CreateCommand())
{
sCommand.CommandText = @"SELECT
TABLE_NAME
AS
TABLES
FROM
INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE
CONSTRAINT_TYPE = 'PRIMARY KEY'
AND
TABLE_NAME <> 'dtProperties'
ORDER BY
TABLE_NAME";
sConnection.Open();
using(var reader = sCommand.ExecuteReader()) // Troublesome line
{
while(reader.Read())
{
sb.AppendLine(reader.GetString(0));
}
}
}
}
catch(Exception ex)
{
//All the exceptions are handled and written in the EventLog.
EventLog log = new EventLog("Application");
log.Source = "MFDBAnalyser";
log.WriteEntry(ex.Message);
}
return sb.ToString();
}
在调试时,它会给出结果,直到连接打开但是var Reader没有读取数据。
任何人都可以指出错误的位置!!
答案 0 :(得分:0)
在MSDN中看到:Reader
while (reader.Read())
{
Console.WriteLine(String.Format("{0}", reader[0]));
}
所以也许尝试使用reader[0]
代替reader.getString(0)
?
修改:
试试这个:
public Form1()
{
InitializeComponent();
String ConnectionString = @"Data Source=SERVER\SQLEXPRESS;Initial Catalog=DBNAME;User ID=USER;Password=PWD";
StringBuilder sb = new StringBuilder();
using (SqlConnection sConnection = new SqlConnection(ConnectionString))
{
String query = @"SELECT TABLE_NAME AS TABLES FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_TYPE = 'PRIMARY KEY' AND TABLE_NAME <> 'dtProperties' ORDER BY TABLE_NAME";
SqlCommand comand = new SqlCommand(query, sConnection);
sConnection.Open();
SqlDataReader reader = comand.ExecuteReader();
if (reader.HasRows)
{
Console.WriteLine("reader.hasRows == true !");
}
else
{
Console.WriteLine("reader.hasRows == FALSE !");
}
while (reader.Read())
{
sb.AppendLine(reader.GetString(0));
}
}
Console.WriteLine(sb.ToString());
}
}
看看它是否有效。
我创建了一个新的Winform应用程序,尝试过,它对我有用。
这是我的输出:
reader.hasRows == true !
Categorie
Chantier
...
And all my table names.
答案 1 :(得分:0)
在创建Command之前尝试放置 Connection.Open()。
答案 2 :(得分:0)
您提供的代码与您运行的代码相同吗?
如果你有自我初始化的get属性,通常会发生调试中“工作”的奇怪行为,但不会出现在运行时。像这样:
private string _name;
public string Name
{
get {
if (_name == null)
{
name = string.Empty;
}
return _name;
}
set {_name = value;}
}
因此,如果您直接使用_name并且调试器显示此类属性,则会在使用前“意外地”初始化您的属性。