[英]Browsing and Uploading a file to database using asp.net and sql server
[英]SQL Server database file connected in asp.net but query not executing
我將.MDF
數據庫文件連接到C#(Visual Studio)中的aspx文件,但是當我嘗試執行查詢時,它不起作用。
下面給出的是發生問題的代碼。 請幫幫我。
com.ExecuteNonQuery()
返回-1,我猜如果成功執行,它應該返回1
SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\karunya\Documents\Visual Studio 2010\Projects\Login\Login\App_Data\MyDB.mdf;Integrated Security=True;User Instance=True");
con.Open();
string sql = "SELECT * FROM Data WHERE user = '"+user.Text+"' ";
SqlCommand com = new SqlCommand(sql, con);
int tmp = Convert.ToInt32(com.ExecuteNonQuery());
con.Close();
if (tmp == 1)
{
con.Open();
sql = "SELECT pass FROM LogTable WHERE user = '" + user.Text + "'";
SqlCommand com1 = new SqlCommand(sql, con);
string password = com1.ExecuteScalar().ToString();
if (password == pass.Text)
{
Response.Write("Access Granted!");
}
else
{
Response.Write("Access Denied!");
}
}
else
{
Response.Write("User Name Incorrect!");
}
您想做什么?
它總是返回-1,因為您正在選擇表
做這個 ..
DataTable dt = new DataTable();
using (var conn = new SqlConnection(connectionLib))
{
try
{
using (var cmd = new SqlCommand(Query, conn))
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
conn.Close();
da.Dispose();
}
}
catch
{
}
}
現在根據您的條件檢查是否要檢查行數,然后檢查
dt.rows.cout
不用依賴ExecuteNonQuery
的返回值,而是在查詢內部使用COUNT(*)
並使用ExecuteScalar
返回計數。
並且總是(總是)使用參數化查詢:
string sql = "SELECT COUNT(*) FROM Data WHERE user = @user";
SqlCommand com = new SqlCommand(sql, con);
com.Parameters.AddWithValue("@user", user.Text);
int tmp = Convert.ToInt32(com.ExecuteScalar());
並將對Close()
的調用移到方法的結尾
請嘗試檢查連接字符串是否正常,然后嘗試以下代碼
您會知道是否選擇了hjas行,而不是想要執行的操作
con.Open();
cmd.Connection = con;
cmd.CommandText = "select * from user where login=@login and pass=@psw";
cmd.Parameters.Add(new SqlParameter("@login", SqlDbType.VarChar, 255)).Value = txtpsedu.Text;
cmd.Parameters.Add(new SqlParameter("@psw", SqlDbType.VarChar, 255)).Value = txtlogin.Text;
dr = cmd.ExecuteReader();
if (dr.Read())
{
//// do what you want here
}
else
{
Response.Write("User Name Incorrect!");
}
dr.Close();
con.Close();
我希望嘗試一下
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.