将值插入SQL数据库的Web服务

本文关键字:Web 服务 数据库 SQL 插入 | 更新日期: 2023-09-27 17:50:17

我正在从windows mobile发送一些数据到webservice。现在我想在webservice中编写一个方法,将这些值插入sql数据库。如何继续。请帮助

将值插入SQL数据库的Web服务

您想要的是一个Restful web服务。

有一本好书叫《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);
}

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