How to add information to database from gridview? - c#

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

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

Jut get as result: System.Data.SqlClient.SqlDataReader

Can someone help me out?
I just get as result tb_localidade: System.Data.SqlClient.SqlDataReader
Why? Here is the code:
private void btn_normalizar_Click(object sender, EventArgs e)
{
//connection string - one or other doenst work
//SqlConnection conn = new SqlConnection("DataSource=FRANCISCO_GP;Initial Catalog=Normalizacao;Integrated Security=True;");
SqlConnection conn = new SqlConnection(Properties.Settings.Default.connString);
string sql = "SELECT ART_DESIG from Arterias where ART_COD = '10110'";
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
SqlDataReader leitor = cmd.ExecuteReader();
tb_localidade.Text = leitor.ToString();
conn.Close();
}
You can do this by calling Read() on your data reader and assigning the results:
private void btn_normalizar_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.connString))
{
conn.Open();
string sql = "SELECT ART_DESIG from Arterias where ART_COD = '10110'";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
SqlDataReader leitor = cmd.ExecuteReader();
while (leitor.Read())
{
tb_localidade.Text = leitor["ART_DESIG"].ToString();
}
}
}
}
Another note is that using a using block for your SqlConnection and SqlCommand objects is a good habit to get into.
Note: this is assigning the result to the tb_localidade.Text for every row in the resultset. If you are only intending for this to be one record, you might want to look into .ExecuteScalar() instead (see below).
private void btn_normalizar_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.connString))
{
conn.Open();
string sql = "SELECT ART_DESIG from Arterias where ART_COD = '10110'";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
tb_localidade.Text = cmd.ExecuteScalar().ToString();
}
}
}
before execute "executeReader()" then you must read to get results.
Improvement on Siyual's response. You're only looking for a single result, and this explicitly disposes both the connection and the datareader.
private void btn_normalizar_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.connString))
{
conn.Open();
string sql = "SELECT ART_DESIG from Arterias where ART_COD = '10110'";
using(SqlCommand cmd = new SqlCommand(sql, conn)) {
using(SqlDataReader leitor = cmd.ExecuteReader())
{
if (leitor.Read())
{
tb_localidade.Text = leitor["ART_DESIG"].ToString();
}
}
}
}
}
you should just this
SqlDataReader leitor = cmd.ExecuteReader();
string res="";
while(leitor.Read())
{
res=leitor.GetValue(0).ToString()///////if in sql it is varchar or nvarshar
}
tb_localidade.Text = res;
actully datareader is a 1d table and we can access to this with GetValue or GetInt32 or ...

MySql error System.InvalidOperationException in windows application-c#

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

Trying to use an INSERT method but not working

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

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.

Categories