我收到错误:
无法从MySql.Data.MysqlClient.MySqlCommand转换为 SqlDataAdapter上的'System.Data.SqlClient.SqlCommand'sda = new SqlDataAdapter(cmd);
string MyConnectionString = "Server=localhost;Database=smsjobs;Uid=root;pwd=root;";
protected void Submit_Click(object sender, EventArgs e)
{
MySqlConnection connection = new MySqlConnection(MyConnectionString);
MySqlCommand cmd; connection.Open();
cmd = connection.CreateCommand();
cmd.CommandText="select * from userdetails where db_mobi=@username and db_pass=@word";
cmd.Parameters.AddWithValue("@username", cn_mobi.Text);
cmd.Parameters.AddWithValue("@word", cn_pass.Text);
SqlDataAdapter sda = new SqlDataAdapter(cmd);// getting error here
DataTable dt = new DataTable();
sda.Fill(dt);
int i = cmd.ExecuteNonQuery();
connection.Close();
if (dt.Rows.Count > 0)
{
Session["id"] = cn_mobi.Text;
Response.Redirect("Redirectform.aspx");
Session.RemoveAll();
}
}
答案 0 :(得分:1)
您正在尝试使用MySqlCommand创建SqlDataAdapter(MS SQL的那个)。有MySqlDataAdapter,所以看起来你需要使用它。 但无论如何,这段代码毫无意义:
SqlDataAdapter sda = new SqlDataAdapter(cmd);// getting error here
DataTable dt = new DataTable();
sda.Fill(dt);
int i = cmd.ExecuteNonQuery();
您正在调用DataAdapter以通过SqlCommand填充DataTable,然后使用ExecuteNonQuery再次调用该SqlCommand。那完全是胡说八道。 您需要将代码更改为此(可能):
string MyConnectionString = "Server=localhost;Database=smsjobs;Uid=root;pwd=root;";
protected void Submit_Click(object sender, EventArgs e) {
using(var connection = new MySqlConnection(MyConnectionString)) {
connection.Open();
var cmd = connection.CreateCommand();
cmd.CommandText="select * from userdetails where db_mobi=@username and db_pass=@word";
cmd.Parameters.AddWithValue("@username", cn_mobi.Text);
cmd.Parameters.AddWithValue("@word", cn_pass.Text);
var reader = cmd.ExecuteReader();
if (reader.HasRows)
{
Session["id"] = cn_mobi.Text;
Response.Redirect("Redirectform.aspx");
Session.RemoveAll();
}
}
}
请注意using
而不是直接connection.Close()
答案 1 :(得分:0)
我认为你应该使用System.Data.OleDb;
命名空间,并且在该命名空间中你有相同的类。您应该使用SqlConnection
代替OleDbConnection
,而不是SqlDataAdapter
,您可以使用OleDbDataAdapter
。
我认为它应该有效。希望这会有所帮助。
答案 2 :(得分:0)
我认为你应该改变
SqlDataAdapter sda = new SqlDataAdapter(cmd);
到
MySqlDataAdapter sda = new MySqlDataAdapter (cmd);
由于SqlDataAdapter不会因MySqlCommand而重载。