废话不多说,直接上代码
- 查询数据
using System;
using System.Data;
using System.Data.SqlClient;
namespace MyDbTest
{
class Program
{
static void Main(string[] args)
{
string myConnection = "Data Source = LAPTOP-J00IJNAU; Initial Catalog = MyBook; User ID = sa; Password = lx960601";
SqlConnection conn = new SqlConnection(myConnection);
conn.Open();
SqlCommand comm = conn.CreateCommand();
comm.Connection = conn;
comm.CommandText = "select * from myProducts";
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(comm);
DataTable dt = new DataTable();
sqlDataAdapter.Fill(dt);
conn.Close();
conn.Dispose();
comm.Dispose();
for(int i = 0; i < dt.Rows.Count; i++)
{
for(int j = 0; j < dt.Columns.Count; j++)
{
Console.Write(dt.Rows[i][j] + " ");
}
Console.WriteLine();
}
Console.ReadKey();
}
}
}
- 向数据库插入一条数据
using System;
using System.Data;
using System.Data.SqlClient;
namespace MyDbTest
{
class Program
{
static void Main(string[] args)
{
string myConnection = "Data Source = LAPTOP-J00IJNAU; Initial Catalog = MyBook; User ID = sa; Password = lx960601";
SqlConnection conn = new SqlConnection(myConnection);
conn.Open();
SqlCommand comm = conn.CreateCommand();
comm.Connection = conn;
comm.CommandText = "insert into myProducts values(@Id,@ProductNum,@ProductName,@Specification,@Unit,@CostPrice)";
comm.Parameters.AddWithValue("@id", "6");
comm.Parameters.AddWithValue("@ProductNum", "37-354-875");
comm.Parameters.AddWithValue("@ProductName", "ViVO X30 Pro");
comm.Parameters.AddWithValue("@Specification", "8GB+128GB");
comm.Parameters.AddWithValue("@Unit", "COP");
comm.Parameters.AddWithValue("@CostPrice", "3499");
comm.ExecuteNonQuery();
conn.Close();
comm.Dispose();
conn.Dispose();
Console.ReadKey();
}
}
}