我开始在 Web 服务中使用事务。我使用 C# 并从事务开始插入。但我不插入数据库。
代码 WebService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data.SqlClient;
using System.Data;
[WebService(Namespace = "example.org")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class WebService : System.Web.Services.WebService
{
SqlConnection conn;
SqlCommand comm1, comm2, comm3;
SqlTransaction trans;
SqlDataAdapter adapter1, adapter2;
DataSet ds1, ds2;
string constring = "Database=transaction;server=localhost;user=sa;password=toon2255";
[WebMethod(Description = "Transaction")]
public string transaction(int userid, int amount)
{
conn = new SqlConnection(constring);
conn.Open();
comm2 = new SqlCommand("INSERT INTO moneytrans VALUES('" + userid + "','" + amount + "')");
trans = conn.BeginTransaction();
comm2.Transaction = trans;
try
{
comm2.ExecuteNonQuery();
trans.Commit();
return "Transaction Complted. ";
}
catch (Exception)
{
trans.Rollback();
return "Transaction Failed..";
}
finally
{
conn.Close();
}
}
}
代码 Default.aspx.cx(网站)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
protected void btnok_Click(object sender, EventArgs e)
{
WSLogin.WebService obj = new WSLogin.WebService();
lblmsg.Text = obj.transaction(Convert.ToInt32(txtuserid.Text), Convert.ToInt32(txtamount.Text));
}
但现在结果“交易失败..”
我想要结果“事务完成”并插入数据库完成。