A simple example of c manipulating an sqlserver database
- 2020-06-23 01:45:54
- OfStack
1. Log in sql server database using windows mode and create a new query:
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. Create a new project in vs and enter the following code:
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(" Link error :" + ex.Message);
}
string sqlMessage=null;
sqlMessage = "select * from student";
SqlCommand sCmd = new SqlCommand(sqlMessage, sConn);
SqlDataReader sdr = null;
try
{
sdr = sCmd.ExecuteReader();
Console.WriteLine(" The name gender age ");
while (sdr.Read())
{
Console.WriteLine(sdr["name"] +""+ sdr["sex"]+"" + sdr["age"]);
}
sConn.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
}
3. The running result will display the data in the database