c#操作sqlserver數據庫的簡略示例。本站提示廣大學習愛好者:(c#操作sqlserver數據庫的簡略示例)文章只能為提供參考,不一定能成為您想要的結果。以下是c#操作sqlserver數據庫的簡略示例正文
1.在用windows形式上岸sql server 數據庫 簡歷一個student的數據庫,然後新建查詢:
create table student
(
id int auto_increment primary key,
name char(10) not null,
sex char(10) not null,
age char(10) not null,
)
2.在vs中新建一個項目,輸出一下代碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string connSting;
connSting = "server=localhost;database=student;Integrated Security=True ";
SqlConnection sConn = new SqlConnection(connSting);
try
{
sConn.Open();
}
catch (Exception ex)
{
Console.WriteLine("鏈接毛病:" + ex.Message);
}
string sqlMessage=null;
sqlMessage = "select * from student";
SqlCommand sCmd = new SqlCommand(sqlMessage, sConn);
SqlDataReader sdr = null;
try
{
sdr = sCmd.ExecuteReader();
Console.WriteLine(" 姓名 性別 年紀 ");
while (sdr.Read())
{
Console.WriteLine(sdr["name"] +""+ sdr["sex"]+"" + sdr["age"]);
}
sConn.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
}
3.運轉成果將會顯示數據庫中的數據