连接对象&一些ado.net部分在插入数据时遇到一些错误,首先这里是我的PHP编码部分。这里我要将php编码转换为.net
openConn();
//<user> slett <slettID>
if((sizeof($MessageArray)==3) && (strtolower($MessageArray[1])=='slett'))
{
$user_id=$MessageArray[2];
if ((int)$user_id > 0)
{
$username=$MessageArray[0];
$QueryCheckMak = "SELECT COUNT(*) FROM XYZ WHERE id='$user_id'";
$QueryCheckMak = odbc_exec($conn, $QueryCheckMak) or die("Query error");
$user_number = odbc_result($QueryCheckMak, 1);
if($user_number=="0")
{
$message_out = "SOME ERROR OUT ";
}
下面的编码是我尝试转换它。我成功转换了部分&amp;字符串到小写part.below这里编码部分使用ODBC连接,但在我的情况下,我sue sql服务器连接
public partial class SeenSMS : System.Web.UI.UserControl
{
public SqlConnection mycon;
SqlConnection con = new SqlConnection(@"Data Source=DSOFT\DOMZ;Initial Catalog=Vilt;UserID=sa;Password=sa123");
protected void Page_Load(object sender, EventArgs e)
{
string[] msg_arr = Request.QueryString["arr"].Split('|');
if (!IsPostBack)
{
string Moose = Request.QueryString[1];
}
if (msg_arr != null)
{
if ((msg_arr.Length == 3) && (msg_arr[1].ToLower() == "slett"))
{
int user_id = Convert.ToInt32(msg_arr[2]);
if(user_id > 0)
{
string username = msg_arr[0];
SqlDataReader rdr = null;
con.open();
SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM XYZ WHERE id='$user_id",con);
if(user_number =='0')
{
Response.WriteLine("ERROR");
// else part here
}
}
}
}
}
答案 0 :(得分:4)
使用这种语法,using
块将自动处理范围末尾的对象
public partial class SeenSMS : System.Web.UI.UserControl
{
string connectionString = "Data Source=DSOFT\DOMZ;Initial Catalog=Vilt;UserID=sa;Password=sa123";
protected void Page_Load(object sender, EventArgs e)
{
....
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
using (SqlCommand command = new SqlCommand("SELECT COUNT(*) FROM TableName WHERE id='" +user_id +"', con))
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
response.Write(reader.GetInt32(0), reader.GetString(1), reader.GetString(2));
}
}
}
....
}
}
答案 1 :(得分:2)
试试这个:
SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM XYZ WHERE user_id=@user_id,con));
oCmd.Parameters.AddWithValue("@user_id", user_id);
int user_number = 0;
con.open();
using (SqlDataReader oReader = cmd.ExecuteReader())
{
while (oReader.Read())
{
user_number =Convert.ToInt32(oReader["count"]);
}
myConnection.Close();
}
if(user_number == 0)
{
Response.WriteLine("ERROR");
// else part here
}