如何使用C#&保存数据SQL Server 2005 [英] How to save data using C# & SQL Server 2005

查看:95
本文介绍了如何使用C#&保存数据SQL Server 2005的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,

我是C#的新手,正在做一个简单的项目.我需要帮助.如何保存在SQL Server中并按ID检索数据.

预先感谢,

Asgar:sigh:

Hello,

I am new to C# and I am doing a simple project. I need help. how to save in SQL Server and retrieve the data by ID.

Thanks in advance,

Asgar :sigh:

推荐答案

您可以阅读初学者通过C#访问SQL Server的指南 [ ^ ]


您可以在此处 [ ^ ].


using System.Data;
using System.Data.SqlClient;

namespace myNamespace
{
class Program
{
Static void Main(string[]args)
{
SqlConnection con=new SqlConnection("server=yourservername;uid=sa;pwd=yourpassword;database=databasename");

//insert the information to the database

SqlCommand cmd=new SqlCommand("Insert into T1(Id,Name)values(@Id,@Name)",con);
Console.Write("Enter the Id:");
cmd.Parameters.Add("@Id",SqlDbType.Int).Value=Convert.ToInt32(Console.ReadLine());
cmd.Parameters.Add("@Name",SqlDbType.VarChar,30).Value=Console.ReadLine();
if(con.State==ConnectionState.Closed)
{
con.Open();
}
int i=cmd.ExecuteNonQuery();
if(i>0)
{
Console.WriteLine("Record Inserted Successfully");
}
else
{
Console.WriteLine("Operation Failed,Please Try Again Later");
}

//Get the information by Id

SqlDataAdapter dad=new SqlDataAdapter("Select * from T1 where Id=@Id",con);
Console.Write("Enter the Id to get the record:");
dad.SelectCommand.Parameters.Add("@Id",SqlDbType.Int).Value=Convert.ToInt32(Console.ReadLine());
DataTable dtbl=new DataTable();
dad.Fill(dtbl);
Console.WriteLine("Id:"+dtbl.Rows[0]["Id"].ToString());
Console.WriteLine("Name:"+dtbl.Rows[0]["Name"].ToString());

}
}
}


这篇关于如何使用C#&保存数据SQL Server 2005的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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