我正在使用一个简单的程序,现在我遇到了一个加密和解密密码并将其存储在数据库中的问题。我正在使用的逻辑是加密密码,但它没有存储在数据库中,而是在下面显示错误
System.Data.SqlClient.SqlException:'='附近的语法不正确。
我的代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
namespace WebApplication5
{
public partial class WebForm6 : System.Web.UI.Page
{
SqlConnection connection;
protected void Page_Load(object sender, EventArgs e)
{
connection = new SqlConnection(ConfigurationManager.ConnectionStrings["TestQueryConnectionString"].ConnectionString);
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
SqlConnection con1 = new SqlConnection(ConfigurationManager.ConnectionStrings["TestQueryConnectionString"].ConnectionString);
con1.Open();
SqlCommand cmd1 = new SqlCommand("select * from admin where USERNAME=@USERNAME and PASSWORD=@PASSWORD ", con1);
cmd1.Parameters.AddWithValue("@username", txtUserName.Text);
cmd1.Parameters.AddWithValue("@password", txtPassword.Text);
SqlDataReader dr = cmd1.ExecuteReader();
if (dr.HasRows)
{
ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('userName is already availables')</script>");
}
else
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TestQueryConnectionString"].ConnectionString);
con.Open();
string strQuery = EncodePasswordToBase64("insert into admin( USERNAME,PASSWORD) values('" + txtUserName.Text + "','" + txtPassword.Text + "')");
connection = new SqlConnection(ConfigurationManager.ConnectionStrings["TestQueryConnectionString"].ConnectionString);
connection.Open();
SqlCommand cmd = new SqlCommand(strQuery, connection);
cmd.ExecuteNonQuery();
connection.Close();
Response.Redirect("login.aspx");
}
con1.Close();
}
public static string EncodePasswordToBase64(string password)
{
try
{
byte[] encData_byte = new byte[password.Length];
encData_byte = System.Text.Encoding.UTF8.GetBytes(password);
string encodedData = Convert.ToBase64String(encData_byte);
return encodedData;
}
catch (Exception ex)
{
throw new Exception("Error in base64Encode" + ex.Message);
}
}
}
}
问题是: 我在这里做错了什么?
答案 0 :(得分:1)
您正在编码完整查询,而只应编码密码
string strQuery = EncodePasswordToBase64("insert ....
应该是:
string strQuery = "insert into admin( USERNAME,PASSWORD) values('" + txtUserName.Text +
"','" + EncodePasswordToBase64(txtPassword.Text) + "')");
你应该使用SqlParameter并进行参数化查询而不是字符串连接
string strQuery = "insert into admin( USERNAME,PASSWORD) values(@pUserName, @pPassword)";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.AddWithValue("@pUserName", txtUserName.Text");
cmd.Parameters.AddWithValue("@pPassword", EncodePasswordToBase64(txtPassword.Text))