Trying to use an INSERT method but not working - c#

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().

Related

How to insert into an identity column in MS SQL

I have the following code:
SqlCommand writeCommand = new SqlCommand("INSERT INTO computers(id)VALUES()", conn.GetConnection());
writeCommand.ExecuteNonQuery();
The table computers contains an INT idientity(1,1) column named id.
When I run the code, I get a System.Data.SqlClient.SqlException: Incorrect syntax near ')'. I've tried to find a solution, but can't find one on the internet.
If the table has other columns as well, and you want to populate them with NULL or their DEFAULT values, then you can use DEFAULT VALUES:
INSERT INTO dbo.computers
DEFAULT VALUES;
If, however, your table only have the one column, then personally using an IDENTITY is the wrong choice; a table that just has an IDENTITY is clearly being misused. Instead, use a SEQUENCE:
CREATE SEQUENCE dbo.Computers START WITH 1 INCREMENT BY 1;
This scales far better, and doesn't suffer the likely race conditions you have. Then, when running an INSERT (or similar) you would use NEXT VALUE FOR dbo.Computers.
For an auto-incrementing identity column the database handles the id value unless I missed something in what you are attempting to do.
public void DemoInsert(string ComputerName, ref int newIdentifier)
{
using (var conn = new SqlConnection { ConnectionString = ConnectionString })
{
using (var cmd = new SqlCommand { Connection = conn })
{
cmd.CommandText = "INSERT INTO computers (ComputerName) " +
"VALUES (#ComputerName); " +
"SELECT CAST(scope_identity() AS int);";
cmd.Parameters.AddWithValue("#ComputerName", ComputerName);
cn.Open();
newIdentifier = (int)cmd.ExecuteScalar();
}
}
}
I have similar code like your app, think about it simple crud app
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SqlConnection con;
SqlDataAdapter da;
SqlCommand cmd;
DataSet ds;
void fillGrid()
{
con = new SqlConnection("Data Source=.;Initial Catalog=schoolDb;Integrated Security=True");
da = new SqlDataAdapter("Select * from ogrenciler",con);
ds = new DataSet();
con.Open();
da.Fill(ds, "students");
dataGridView1.DataSource = ds.Tables["students"];
con.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
fillGrid();
}
private void Addbtn_Click(object sender, EventArgs e)
{
cmd = new SqlCommand();
con.Open();
cmd.Connection = con;
cmd.CommandText="insert into students(StudentId,StudentName,StudentSurname,City) values("+StudentId.Text+",'"+StudentName.Text+"','"+StudentSurname.Text+"','"+City.Text+"')";
cmd.ExecuteNonQuery();
con.Close();
fillGrid();
}
private void Updatebtn_Click(object sender, EventArgs e)
{
cmd = new SqlCommand();
con.Open();
cmd.Connection = con;
cmd.CommandText = "update Students set ogrenci_ad='"+StudentName.Text+"',StudentName='"+StudentSurname.Text+"',City='"+City.Text+"' where StudentId="+StudentId.Text+"";
cmd.ExecuteNonQuery();
con.Close();
fillGrid();
}
private void Deletebtn_Click(object sender, EventArgs e)
{
cmd = new SqlCommand();
con.Open();
cmd.Connection = con;
cmd.CommandText = "delete from ogrenciler where ogrenci_no="+StudentId.Text+"";
cmd.ExecuteNonQuery();
con.Close();
fillGrid();
}
}
}

Proper way of closing sql connection - without using MARS

My client server is not supporting MARS. So I need to close each sql connection after executing each query. But I have doubt on closing connection when its coming to multiple nested loop query .
My code is
protected void btn_upload_Click(object sender, ImageClickEventArgs e)
{
try
{
SqlConnection con = obj.getcon();
con.Open();
SqlCommand cmd77 = new SqlCommand("select * from emp_details where emp_id='"+emp_id+"'", con);
SqlDataReader dr77 = cmd77.ExecuteReader();
if (dr77.HasRows)//dont insert if employee already exist
{
string query1 = "UPDATE emp_details SET emp_name= #emp_name where emp_id=#emp_id";
SqlCommand cmd = new SqlCommand(query1, con);
cmd.Parameters.Add(new SqlParameter("emp_id", emp_id));
cmd.Parameters.Add(new SqlParameter("emp_name", emp_name))
cmd.ExecuteNonQuery();
}
else
{
insertdataintosql(GetempID,GetempName);
}
con.Close();
}
catch (Exception ex)
{
string ex=ex.Message;
}
}
public void insertdataintosql(string emp_id, string emp_name)
{
SqlConnection con = obj.getcon();
con.Open();
string query = "insert into emp_details(emp_id,emp_name) values(#emp_id,#emp_name)";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.Add(new SqlParameter("emp_id", emp_id));
cmd.Parameters.Add(new SqlParameter("emp_name", emp_name))
cmd.ExecuteNonQuery();
con.Close();
}
Where should I close the first connection for SqlDataReader (dr77) since it is used in if else loop? If not using MARS , Shall I need to open/close a new connection on update query? So is it necessary to close dr77 to before it?

SQL parameters not working

This is the code I'm working with right now, I don't get any errors so I can't pinpoint where it's not working:
private void btnAdd_Click(object sender, EventArgs e)
{
string constring = $"Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=" +
Directory.GetCurrentDirectory().ToString() + "\\BarcodeDB.mdf;Integrated Security=True";
string query =
"INSERT INTO Products (Barcodes, Name, EDate, Quantity, Price) VALUES (#barcodeValue, #nameValue, #dateValue, #quantityValue, #priceValue) ;";
SqlConnection conDataBase = new SqlConnection(constring);
conDataBase.Open();
using (var cmd = new SqlCommand(query, conDataBase))
{
cmd.Parameters.AddWithValue("#barcodeValue", tbxBar.Text);
cmd.Parameters.AddWithValue("#nameValue", tbxName.Text);
cmd.Parameters.AddWithValue("#dateValue", dateDate.Value.Date);
cmd.Parameters.AddWithValue("#quantityeValue", tbxQua.Text);
cmd.Parameters.AddWithValue("#priceValue", tbxPrice.Text);
}
conDataBase.Close();
}
The code might just be wrongly build or I could be missing some part I'm not sure.
I figured out what was not working, was the connection string. So opening a new question for that.
What i had to do is to open the connection and then execute the command
You're not actually running the command. You need to call ExecuteNonQuery or ExecuteScalar:
using (var cmd = new SqlCommand(query, conDataBase))
{
// set parameters...
cmd.ExecuteNonQuery();
}

Can I call a sql command parameter from another class?

I have 14 tables, with the usual sql common command parameters, insert, update etc. Beginners, like me, will have all the methods in the main class, like this...
namespace TestApp
{
public partial class TestNamTxt : Form
{
private OleDbConnection myCon;
public TestNamTxt()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
myCon = new OleDbConnection();
myCon.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C\:...
Database2.mdb")
myCon.Open();
ds1 = new DataSet();
string sql = "SELECT * FROM Table1";
da = new System.Data.OleDb.OleDbDataAdapter(sql,myCon);
da.Fill(ds1, "Foo");
myCon.Close();
};
private void Insertbtn_Click(object sender, EventArgs e)
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO Table1 (ID, Name)";
cmd.Parameters.AddWithValue("#ID", IDTxt.Text);
cmd.Parameters.AddWithValue("#Name", NameTxt.Text);
cmd.Connection=myCon;
myCon.Open();
cmd.ExecuteNonQuery();
myCon.Close();
}
}
Could I place code the above code in another class and in the Insertbtn method use the this method? Is there any tutorials or perhaps someone could demonstrate how this could be done? I am not sure what it is called on the description I have given here? Thanks in advance
Sure you can. You can place GetConnection and Insert into separate class(or even leave in Form, but I don't recommend this) and use them as follows:
public static OleDbConnection GetConnection()
{
var myCon = new OleDbConnection();
myCon.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C\:... Database2.mdb";
return myCon;
}
public static void Insert(string id, string name)
{
var con = GetConnection();
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO Table1 (ID, Name)";
cmd.Parameters.AddWithValue("#ID", id);
cmd.Parameters.AddWithValue("#Name", name);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
private void Insertbtn_Click(object sender, EventArgs e)
{
Insert(IDTxt.Text, NameTxt.Text);
}
You can also specify Table name as method parameter if you need.
If i have understood your question correctly
then ya you can do this.
Basically you are trying to use DAL(Data Access Layer) the term used for this,
well its simple,
place the above code into another class and then make an object of that class in this class and use it.
public class DataClass
{
public static bool AddEmp(string id, string name)
{
bool result;
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO Table1 (ID, Name)";
cmd.Parameters.AddWithValue("#ID", id);
cmd.Parameters.AddWithValue("#name", name);
cmd.Connection=myCon;
try
{
myCon.Open();
cmd.ExecuteNonQuery();
result = true;
}
catch
{
result = false;
}
myCon.Close();
return result;
}
and then in the insert function do it like this
private void Insertbtn_Click(object sender, EventArgs e)
{
DataClass ob = new DataClass();
bool returnResult = ob.AddEmp(IDtxt.txt, NameTxt.text)
if(bool) // if result == true
//dosomething
else
// do something
}
Hope it helps.
Your TestNam class is derived from the Form class. Any form event handler you want to define must be a member function of TestNam, but within this function you can do what you want, including passing a reference to the active instance of the form.
If your functions are specific to the form class, put them in the class, if they're shared, you can put htem in another object.

How to add information to database from gridview?

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();
}
}

Categories