C#调用Server_SQL

C#调用Server_SQL:
SqlCommand:数据库命令行语句
//数据库路径
static string GetConnectString()
{
  return "data source=192.168.0.96;initial catalog=haha;user id=sa;pwd=zhao";
}

插入数据库信息
private void InsetSQL()
{
  using (SqlConnection conn = new SqlConnection(GetConnectString()))
  {
    // 打开数据库
    conn.Open();

    //插入数据
    string str = "INSERT INTO[haha].[dbo].[student] VALUES('wwww', '111', 'hahhhh')";
    SqlCommand sqlc = new SqlCommand(str, conn);

    //操作个数
    label1.Text = sqlc.ExecuteNonQuery().ToString();

    //关闭数据库连接
    conn.Close();
  }
}

//查询数据库信息label显示
private void SelectSQL()
{
  using (SqlConnection conn = new SqlConnection(GetConnectString()))
  {
  //打开数据库
  conn.Open();

  //创建数据库命令
  SqlCommand cmd = conn.CreateCommand();

  //创建查询语句
  cmd.CommandText = "SELECT * FROM [haha].[dbo].[student]";

  //从数据库中读取数据流存入reader中
  SqlDataReader reader = cmd.ExecuteReader();
  //从reader中读取下一行数据,如果没有数据,reader.Read()返回flase
  while (reader.Read())
  {
      string name = reader.GetString(reader.GetOrdinal("name"));
      int age = reader.GetInt32(reader.GetOrdinal("age"));
      string gender = reader.GetString(reader.GetOrdinal("gender"));
      //格式输出数据
      label2.Text = label2.Text + "\n" + (name + "," + age + "," + gender);
  }

  //关闭数据库连接
  conn.Close();
  }
}

删除数据库信息
private void InsetSQL()
{

  using (SqlConnection conn = new SqlConnection(GetConnectString()))
  {
    // 打开数据库
    conn.Open();

    //删除数据 命令操作
    string sql = "DELETE FROM haha.dbo.student where name = 'wwww '";

    SqlCommand cmd = conn.CreateCommand();
    cmd.CommandText = sql;

    label3.Text = cmd.ExecuteNonQuery().ToString();

    //关闭数据库连接
    conn.Close();
  }
}

你可能感兴趣的:(C#调用Server_SQL)