Web服务将值插入sql数据库

时间:2011-04-14 15:45:34

标签: c# sql web-services

我正在从Windows Mobile向网络服务发送一些数据。现在我想在Web服务中编写一个方法,将这些值插入到sql数据库中。如何进行。请帮忙

3 个答案:

答案 0 :(得分:1)

您想要的是Restful网络服务。该链接是您的基本方法。

答案 1 :(得分:1)

有一本名为“实用数据库编程”的好书,由ying bai用visual c#.NET编写。

//base class
public class SQLInsertBase
{
  public bool SQLInsertOK;
  public string SQLInsertError;
  public string lat;
  public string lon;
  public string id;
  public SQLInsertBase()
{
    //
    // TODO: Add constructor logic here
    //
   }
}



  [WebMethod]
public SQLInsertBase GetSQLInsertCourse(string id,string lat,string lon)
{
    string cmdString = "INSERT into Location values(@id,@latitude,@longitude)";
    SqlConnection sqlConnection = new SqlConnection();
    SQLInsertBase GetSQLResult = new SQLInsertBase();
    SqlDataReader sqlReader;
    GetSQLResult.SQLInsertOK = true;
    sqlConnection = SQLConn();
    if (sqlConnection == null)
    {
        GetSQLResult.SQLInsertError = "Database connection is failed";
        ReportError1(GetSQLResult);
        return null;
    }
    SqlCommand sqlCommand = new SqlCommand(cmdString, sqlConnection);
    sqlCommand.CommandType = CommandType.Text;
    sqlCommand.Parameters.Add("@id", SqlDbType.Text).Value = id;
    sqlCommand.Parameters.Add("@latitude", SqlDbType.Text).Value = lat;
    sqlCommand.Parameters.Add("@longitude", SqlDbType.Text).Value = lon;
    int result = sqlCommand.ExecuteNonQuery();
  //  if (sqlReader.HasRows == true)
   //     FillCourseDetail(ref GetSQLResult, sqlReader);
    if (result == 0)
    {
        GetSQLResult.SQLInsertError = "cannot update ";
        ReportError1(GetSQLResult);
    }
   /* else
    {
        GetSQLResult.SQLInsertError = "No matched  found";
        ReportError1(GetSQLResult);
    }*/
  //  sqlReader.Close();
    sqlConnection.Close();
    sqlCommand.Dispose();
    return GetSQLResult;
}


 protected SqlConnection SQLConn()
  {
    string cmdString =     ConfigurationManager.ConnectionStrings["sql_conn"].ConnectionString;
    SqlConnection conn = new SqlConnection();
    conn.ConnectionString = cmdString;
    conn.Open();
    if (conn.State != System.Data.ConnectionState.Open)
    {
        MessageBox.Show("Database Open  failed");
        conn = null;
    }
    return conn;
}


protected void ReportError1(SQLInsertBase ErrSource)
{
    ErrSource.SQLInsertOK = false;
    MessageBox.Show(ErrSource.SQLInsertError);
}

答案 2 :(得分:0)

您可能需要查看 Linq To SQL ,它可以很好地将存储过程封装到c#方法中,以便您可以访问数据。您也可以使用它来读取和更新表,但我个人更喜欢存储过程。