C# SQL Server Howto

为项目组写了几个Howto的Case。

本文描述了一个用C#实现的简单的SQL Server查询。
功能是每次执行插入一行记录,然后输出全部记录。

Program.cs
[code=’c#’]
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;

namespace SQLServerHowto
{
class Program
{
static void Main(string[] args)
{
SqlConnection myConnection = new SqlConnection(“Data Source=itsdbserver;user id=its;password=its;database=ITSTestDB”);
myConnection.Open();

string sql = “insert into news (news) values (@value)”;
SqlCommand sc = new SqlCommand(sql, myConnection);
SqlParameter param = new SqlParameter(“value”, “现在是” + DateTime.Now.ToString() + “,但毛君还是垃圾”);
sc.Parameters.Add(param);

int count = sc.ExecuteNonQuery();
Console.WriteLine(“Line inserted: ” + count.ToString());

string sql2 = “select * from News”;
SqlCommand sc2 = new SqlCommand(sql2, myConnection);
SqlDataReader reader = sc2.ExecuteReader();

while (reader.Read())
{
Console.WriteLine(String.Format(“ID={0}, news={1}”, reader[0], reader[1]));
}
}
}
}
[/code]

下载:用Visual Studio 2008打开
http://download.nocoo.us/Download/Archive/CSharpHowto/SQLServer.rar

发表评论