我想用c#选择Table Column属性。我写了这段代码。我的查询正在处理sqlserver。但是我没有在c#中获得最大长度。
我的查询就在这里
//TableName:Contents, ColumnName : Title
select Col_Length('Contents','Title') as columnLengthh
结果在这里:
我的C#代码:
string columnLength = "select Col_Length('Contents','Title') as columnLengthh";
adapter = new SqlDataAdapter(columnLength, connection);
dataSet = new DataSet();
adapter.Fill(dataSet);
DataTable dataTable2 = dataSet.Tables[0];
foreach (DataRow row in dataTable2.Rows)
{
var x = row["columnLengthh"].ToString();
}
结果(x = -1)
我如何在c#中获得长度。
请帮忙!
答案 0 :(得分:2)
检查您的查询是否正确
更改connectionString以匹配您所拥有的 - 例如:
string connectionString = @"server=localhost\mysqlserver;database=master;Trusted_Connection=True;";
并使用以下代码:
string queryString = "select Col_Length('Contents','Title') as columnLengthh";
string connectionString = @"your con string";
SqlConnection connection = null;
try
{
connection = new SqlConnection(connectionString);
using (SqlCommand command = new SqlCommand(queryString, connection))
{
connection.Open();
var result = command.ExecuteScalar();
Console.WriteLine("columnLengthh = {0}", result);
}
}
catch (Exception ex)
{
ex.ToString();
}
finally
{
connection.Close();
}
答案 1 :(得分:1)
只需使用SqlConnection
,SqlCommand
,SqlReader
等类与SQL Server进行通信。
string queryString = "select Col_Length('Contents','Title') as columnLengthh";
string connectionString = "Your connection string";
SqlConnection connection = null;
try
{
connection = new SqlConnection(connectionString)
using (SqlCommand command = new SqlCommand(queryString, connection)) ;
{
connection.Open();
var result = command.ExecuteScalar();
Console.WriteLine("columnLengthh = {0}", result);
}
}
finally
{
connection.Close();
}