I am getting the error:
An unhandled exception of type 'System.InvalidOperationException'
occurred in MySql.Data.CF.dll
in my windows application program.
Below is my code.
In app.config:
inside connectionStrings tag
add name="ConnectionString"
connectionString="server=localhost;database=my_db;user=root;port=3306;
password=mypwd;
In LoginForms.cs
using System.Configuration;
using MySql.Data.MySqlClient;
namespace MySoftware
{
public partial class Login : Form
{
MySqlConnection conn;
public static int valid = 0;
public Login()
{
InitializeComponent();
}
private void btnLogin_Click(object sender, EventArgs e)
{
var connectionString =
ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
conn = new MySqlConnection(connectionString);
conn.open();
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = "Verify_Login";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#uname", textBox1.Text);
cmd.Parameters["#uname"].Direction = ParameterDirection.Input;
cmd.Parameters.AddWithValue("#pwd", textBox2.Text);
cmd.Parameters["#pwd"].Direction = ParameterDirection.Input;
cmd.Parameters.AddWithValue("#result", MySqlDbType.Int32);
cmd.Parameters["#result"].Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery(); // At this line the error is thrown
int valid = (int)(cmd.Parameters["#result"].Value);
}
}
}
Verify_Login is a stored procedure which is created in MySQL as below.
CREATE PROCEDURE `Verify_Login`(in uname varchar(20),in pwd varchar(20),out
result bool)
BEGIN
select count(*) into result from Login where uname=uname and password=pwd;
END
Could anyone please help me with this?
Your code fails because is trying to execute a command and this command is not bound to an open connection. You have a lot of ways to bind the connection
MySqlCommand cmd = conn.CreateCommand();
or
MySqlCommand cmd = new MySqlCommand(sqlText, conn);
or
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conn;
Of course the suggestion to use the appropriate Connector for your environment still stands....
Your code refactored a bit
private void btnLogin_Click(object sender, EventArgs e)
{
var connectionString =
ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
using(MySqlConnection conn = new MySqlConnection(connectionString))
using(MySqlCommand cmd = new conn.CreateCommand())
{
conn.open();
cmd.CommandText = "Verify_Login";
cmd.CommandType = CommandType.StoredProcedure;
.....
cmd.ExecuteNonQuery();
int valid = (int)(cmd.Parameters["#result"].Value);
}
}
Related
I have an update statement that works fine when I run it from SQL Developer. However, when I try to run it in C#, the program will freeze on the line that executes the command and not output anything. I have it defined as follows below:
private static OracleCommand cmd = new OracleCommand();
private static OracleConnection conn = new OracleConnection();
conn.ConnectionString = Properties.Settings.Default.myconstring;
cmd.Connection = conn;
cmd.CommandText = "UPDATE mytable SET PARAM1 = :param1 WHERE PARAM2 = :param2";
cmd.CommandType = CommandType.Text;
cmd.BindByName = true;
cmd.Parameters.Clear();
cmd.Parameters.Add(new OracleParameter(":param1", OracleDbType.Single)).Value = param1Val;
cmd.Parameters.Add(new OracleParameter(":param2", OracleDbType.Int32)).Value = param2Val;
conn.Open();
try {
cmd.ExecuteNonQuery(); //Freezes here
} catch(Exception e) {
MessageBox.Show(e.ToString());
}
conn.Close();
I have verified my values being put in are correct.
I am c#.net newbie. This is my form table.
First Name: <asp:TextBox ID="f_name" runat="server"></asp:TextBox>
<asp:Button ID="btnInsertion" runat="server" Text="Insert"
OnClick="btnInsertion_Click" />
I need help on solving this two error in visual basic. This is my xxxx.aspx.cs which giving me two CS0103 error
-f_name does not exist in the context.
-txtFname does not exist in the context.
protected void btnInsertion_Click(object sender, EventArgs e)
{
using (NpgsqlConnection connection = new NpgsqlConnection())
{
connection.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ToString();
connection.Open();
NpgsqlCommand cmd = new NpgsqlCommand();
cmd.Connection = connection;
cmd.CommandText = "Insert into student_folio values(#f_name)";
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add(new NpgsqlParameter(#f_name, txtFname.Text));
cmd.ExecuteNonQuery();
cmd.Dispose();
connection.Close();
txtFname.Text = ""; s
}
}
i think you have forgotten to enclose #f_name in Parameters.Add(, also txtFname is not within the scope, is it existing on the page you are accessing btnInsertion?
protected void btnInsertion_Click(object sender, EventArgs e)
{
using (NpgsqlConnection connection = new NpgsqlConnection())
{
connection.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ToString();
connection.Open();
NpgsqlCommand cmd = new NpgsqlCommand();
cmd.Connection = connection;
cmd.CommandText = "Insert into student_folio (fieldname) values(#f_name)";
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add(new NpgsqlParameter("f_name", txtFname.Text));
cmd.ExecuteNonQuery();
cmd.Dispose();
connection.Close();
txtFname.Text = "";
}
}
I am using asp.net with c# and there exist an error in these line of codes.
protected void btnsubmit_Click(object sender, EventArgs e)
{
string type = "c";
string FID = Session["FID"].ToString();
SqlConnection cn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
//int str_diff = Convert.ToInt32(ConfigurationManager.AppSettings["Difference"]);
cn.ConnectionString = #"Data Source=BOPSERVER;Initial Catalog=Project;Integrated Security=True";
cn.Open();
cmd.CommandText = "update TrackingFaculty_det SET Type=#Type WHERE (FID=#FID) and DATEDIFF(d,TrackingFaculty_det.LastUpdateDate,GETDATE())>60";
cmd.Parameters.Add("#FID",SqlDbType.VarChar,10);
cmd.Parameters["#FID"].Value = FID;
cmd.Parameters.Add("#Type", SqlDbType.VarChar, 1);
cmd.Parameters["#Type"].Value = type;
cmd.ExecuteNonQuery();
cn.Close();
Response.Redirect("~/Faculty/Personaldet.aspx");
}
You haven't set the connection to the command
cmd.Connection = cn;
You need to assign the SqlConnection to the SqlCommand. As an additional suggestion I would wrap the connection in a using block to ensure it is correctly disposed in the case of an exception.
using (SqlConnection cn = new SqlConnection(#"Data Source=BOPSERVER;Initial Catalog=Project;Integrated Security=True")
{
cn.Open();
SqlCommand cmd = new SqlCommand("update TrackingFaculty_det SET Type=#Type WHERE (FID=#FID) and DATEDIFF(d,TrackingFaculty_det.LastUpdateDate,GETDATE())>60", cn);
cmd.Parameters.Add("#FID",SqlDbType.VarChar,10);
cmd.Parameters["#FID"].Value = FID;
cmd.Parameters.Add("#Type", SqlDbType.VarChar, 1);
cmd.Parameters["#Type"].Value = type;
cmd.ExecuteNonQuery();
}
SqlCommand cmd = new SqlCommand("update TrackingFaculty_det SET Type=#Type WHERE (FID=#FID) and DATEDIFF(d,TrackingFaculty_det.LastUpdateDate,GETDATE())>60", cn);
cmd.Parameters.Add("#FID",SqlDbType.VarChar,10);
cmd.Parameters["#FID"].Value = FID;
cmd.Parameters.Add("#Type", SqlDbType.VarChar, 1);
cmd.Parameters["#Type"].Value = type;
cmd.ExecuteNonQuery();
i'm trying to use an insert method in my studentHelperClass, I am trying to activate it on a button click on my form, I don't know how to make it work with a text box, so if someone could help with that, that would be great.
This is my method:
public static void insertStudent()
{
MySqlConnection conn = connection();
conn.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conn;
string myInsertSQL = "INSERT INTO person(personID) ";
cmd.Prepare();
myInsertSQL += "VALUES (#personID)";
cmd.Parameters.AddWithValue("#personID", "123345667788");
prevID(conn, cmd);
}
and this is my form:
private void btnInsert_Click(object sender, EventArgs e)
{
studentHelperClass.insertStudent();
}
EDIT:
private static void prevID(MySqlConnection conn, MySqlCommand cmd)
{
conn.Open();
cmd.ExecuteNonQuery();
long studentNumber = (long)cmd.LastInsertedId;
Console.Write("previous id {0} ", studentNumber);
Console.ReadLine();
conn.Close();
}
Considering the information, assuming that your prevId(conn,cmd) is calling ExecuteNonQuery, you will still need to set the cmd.CommandText to be equal to your myInsertSql (as other answers have pointed out).
To answer your question though,
private void btnInsert_Click(object sender, EventArgs e)
{
studentHelperClass.insertStudent(studentIdTextBox.Text);
}
public static void insertStudent(string studentId)
{
MySqlConnection conn = connection();
conn.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = conn;
string myInsertSQL = "INSERT INTO person(personID) ";
cmd.Prepare();
myInsertSQL += "VALUES (?personID)";
cmd.CommandText = myInsertSQL;
cmd.Parameters.AddWithValue("?personID", studentId);
prevID(conn, cmd);
}
Ive also assumed your studentId is a string. If the database has it as a bigint, you will have to do the proper long.TryParse() call.
You need to set cmd.CommandText as myInsertSQL
and also need to call cmd.ExecuteNonQuery()
string sql = "INSERT INTO person (personID) VALUES (#personID)";
using (MySqlConnection conn = connection())
using (MySqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("#personID", personID);
conn.Open();
cmd.ExecuteNonQuery();
}
You must assign your string variable, 'myInsertSQL' to cmd.CommandText, and then call, cmd.ExecuteNonQuery();
I.e.
cmd.CommandText = myInsertSQL;
cmd.ExecuteNonQuery();
cmd.Dispose();
Always call 'Dispose();' when finished so the .net Garbage Collection can cleanup and manage resources.
You don't use the myInsertSQL string at all, you just set it. You have to set the string as the command text by cmd.CommandText = myInsertSQL and you have to call the method cmd.ExecuteNonQuery().
I have been trying to add new information to my database from a Windows Form (Gridview). This is the method I came up with (but it doesn't work):
private void agregarProducto(string id_producto, string id_proveedor, string id_categoria, string cantidad, string precio_actual, string codigo_barras)
{
MySqlCommand cmd = new MySqlCommand();
using (cmd = cn.CreateCommand())
{
cmd.CommandText = "INSERT INTO productos(id_producto, id_proveedor, id_categoria, cantidad, precio_actual, codigo_barras) VALUES (#id_producto, #id_proveedor, #id_categoria, #cantidad, #precio_actual, #codigo_barras)";
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#id_producto", tbId_Prod);
cmd.Parameters.AddWithValue("#id_categoria", tbId_categoria);
cmd.Parameters.AddWithValue("#id_proveedor", tb_Id_proveedor);
cmd.Parameters.AddWithValue("#cantidad", tbCantidad);
cmd.Parameters.AddWithValue("#precio_actual", tbPrecioActual);
cmd.Parameters.AddWithValue("#codigo_barras", tbCod_barras);
cn.Open();
}
}
This is the event that's is supposedly calling it:
private void btAgregarNuevo_Click(object sender, EventArgs e)
{
agregarProducto(tbId_Prod.Text, tb_Id_proveedor.Text, tbId_categoria.Text, tbCantidad.Text, tbPrecioActual.Text, tbCod_barras.Text);
}
Am I missing something?
You haven't executed the sql. Do this after you open the connection
cmd.ExecuteNoneQuery();
private void agregarProducto(string id_producto, string id_proveedor, string id_categoria, string cantidad, string precio_actual, string codigo_barras)
{
MySqlCommand cmd = new MySqlCommand();
using (cmd = cn.CreateCommand())
{
cmd.CommandText = "INSERT INTO productos(id_producto, id_proveedor, id_categoria, cantidad, precio_actual, codigo_barras) VALUES (#id_producto, #id_proveedor, #id_categoria, #cantidad, #precio_actual, #codigo_barras)";
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#id_producto", tbId_Prod);
cmd.Parameters.AddWithValue("#id_categoria", tbId_categoria);
cmd.Parameters.AddWithValue("#id_proveedor", tb_Id_proveedor);
cmd.Parameters.AddWithValue("#cantidad", tbCantidad);
cmd.Parameters.AddWithValue("#precio_actual", tbPrecioActual);
cmd.Parameters.AddWithValue("#codigo_barras", tbCod_barras);
cn.Open();
cmd.ExecuteNoneQuery();//This is the line you are missing
cn.Close();
}
}