如何获取表的主键 [英] How to obtain primary key of table

查看:123
本文介绍了如何获取表的主键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我想知道在sql server数据库中定义了主键的列。

以下是我的代码



 SqlConnection con = new SqlConnection(Initial Catalog = Dbname; Data Source = MySqlServer; User = testuser; Password = pass123;); 

DataSet ds = new DataSet();

SqlCommand cmd = new SqlCommand(select * from TableName,con);
cmd.CommandType = CommandType.Text;

SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);

DataColumn []列;
columns = ds.Tables [0] .PrimaryKey;

//获取数组中的元素数量。
Response.Write(Column Count:+ columns.Length);
for(int i = 0; i< columns.Length; i ++)
{
Response.Write(columns [i] .ColumnName + columns [i] .DataType);
}



事实上,我已经在

 TableName 


但我的代码返回零计数。

请纠正我,如果我错了并提供替代解决方案

感谢提前。

解决方案

阅读以下内容: http://stackoverflow.com/questions/3930338/sql-server-get-table-primary-key-using-sql-query [ ^ ]


我得到了答案......

 da.MissingSchemaAction = MissingSchemaAction.AddWithKey; 



then

 da.Fill(ds); 





它有效......


Hi,
I want to know column which has primary key defined in sql server database.
Following is my code

    SqlConnection con = new SqlConnection("Initial Catalog=Dbname; Data Source=MySqlServer; User=testuser; Password=pass123;");

    DataSet ds = new DataSet();

SqlCommand cmd = new SqlCommand("select * from TableName", con);
        cmd.CommandType = CommandType.Text;

        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(ds);

        DataColumn[] columns;
        columns = ds.Tables[0].PrimaryKey;

        // Get the number of elements in the array.
         Response.Write("Column Count: " + columns.Length);
        for (int i = 0; i < columns.Length; i++)
        {
            Response.Write(columns[i].ColumnName + columns[i].DataType);
        }


In fact, i have defined one primary key on a column of

TableName


But my code returns zero count.
please correct me, if i am wrong and provide me alternative solution
thank is advance.

解决方案

Read the following : http://stackoverflow.com/questions/3930338/sql-server-get-table-primary-key-using-sql-query[^]


I got the answer......

da.MissingSchemaAction = MissingSchemaAction.AddWithKey;


then

da.Fill(ds);



It worked......


这篇关于如何获取表的主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆