Multiple "Insert Into" operation under same event - c#

Guys I searched around like hell but nothing could help me so I think it's time to ask. Before I write to problem, I need to say that I need it's solution asap because it's a project that I have to give tomorrow and I stuck on the same subject since ages and still losing time.
OK here it is;
I need to add a book to a library system, at first phase I add the standard book features which has only "one value" like (name, page number, publishing time, publisherID etc) but as wanted by me book MAY HAVE MULTIPLE WRITERS AND CATEGORIES which killed me and still I can't resolve. I tried to add book to it's (books) table then with the information i got from that i did an other insert op. to (bookWriters) table. While I check it, compiler does everything in order without error but when I check table from SQL Server there is nothing.
Here is what I tried to do;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.SqlClient;
namespace Project_
{
public partial class addBook: Form
{
public addBook()
{
InitializeComponent();
}
public main refForm;
int chosenWritersNumber; //how many writers have selected on listbox
int[] writers= { }; // an array list that i keep writerIDs that comes from class
int ind = 0;
int insertedBookID; // to catch latest added book's ID
int chosenWriterID; // writer that will be added
private void bookAddingPreps()
{
chosenWritersNumber = lstWriters.SelectedItems.Count;
Array.Resize<int>(ref writers, chosenWritersNumber );
for (int i = 0; i < chosenWritersNumber ; i++)
{
writers[i] = ((X_Writers)lstWriters.SelectedItems[i]).XWriterID;
}
}
private void addMainBookInfos()
{
SqlConnection con = new SqlConnection(Conn.Activated);
SqlCommand com = new SqlCommand("AddBook", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#BookISBN", txtISBN.Text);
con.Close();
}
private void catchAddedBookID()
{
SqlConnection con = new SqlConnection(Conn.Activated);
SqlCommand com = new SqlCommand("catchBookID", con);
com.CommandType = CommandType.StoredProcedure;
con.Open();
SqlDataReader dr = com.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
insertedBookID = dr.GetInt32(0);
}
}
dr.Close();
con.Close();
}
private void addWritersOfTheBook()
{
chosenWriterID = writers[ind];
SqlConnection con = new SqlConnection(Conn.Activated);
SqlCommand com = new SqlCommand("addBookWriters", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#BookID", insertedBookID);
com.Parameters.AddWithValue("#WriterID", chosenWriterID);
con.Close();
}
I call these methods on click of a button. You see also stored procedure names but as I checked they all correct, there must be a mistake in this page that I still cant see but if it's needed I can add what procedures writes but they all tested and seems working.
So as i said, when i do this, as ind = 0, a writer should have been added, break point shows everything is ok and compiler doesnt show any errors but when I check sql server table, its empty.
Written in C# with using Visual Studio 2010 Ultimate and SQL Server 2008 Dev.
Thanks

You forget to execute your SqlCommand's. Make a call to command.ExecuteNonReader(); to execute it without expecting any results. see: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.aspx
Apart form that, dont forget to dispose the resources acquired in your methods. Something like:
private void addMainBookInfos()
{
using (SqlConnection con = new SqlConnection(Conn.Activated))
using (SqlCommand com = new SqlCommand("AddBook", con))
{
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#BookISBN", txtISBN.Text);
com.ExecuteNonQuery()
// close can be omitted since you are already using the 'using' statement which automatically closes the connection
con.Close();
}
}

Related

how to solve exception for the connection string(local database c#)

ok so the first problem is the connection string itself it has this exception that i do not understand so i tried to put it in a try catch syntax but as i inserted it in the public partial class Form1 : Form the parenthesis are acting up so i inserted it in a function and now the fuction has this error:
Severity Code Description Project File Line Suppression State
Error CS0161 'Form1.connection()': not all code paths return a value Restaurant Management System C:\Users\admin\source\repos\Restaurant Management System\Restaurant Management System\Form1.cs 36 Active
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace Restaurant_Management_System
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
panel1.BackColor = Color.FromArgb(50, Color.Black);
label1.BackColor = Color.FromArgb(30, Color.Beige);
label2.BackColor = Color.FromArgb(0, Color.Black);
Password.BackColor = Color.FromArgb(0, Color.Black);
}
SqlCommand cmd;
SqlDataReader dr;
public SqlConnection connection()
{
try
{
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename= \"|Data Directory|\\Coffee(LoginEmployee).mdf\";Integrated Security=True;");
}
catch (Exception ex)
{
MessageBox.Show("Error message: COULD NOT CONNECT STRING: " + ex);
}
}
private string getUsername()
{
SqlConnection con = connection();
cmd = new SqlCommand("SELECT nalue FROM EmployeeLog where Property=Username", con);
dr = cmd.ExecuteReader();
dr.Read();
return dr[0].ToString();
}
private string getPassword()
{
SqlConnection con = connection();
cmd = new SqlCommand("SELECT nalue FROM EmployeeLog where Property=Password", con);
dr = cmd.ExecuteReader();
dr.Read();
return dr[0].ToString();
}
What do i need to replace? why does it not all return a value? if i use the void case it will also have this error that i cannot explicitly convert it to sqlconnection. this is made in the latest visual studio 2017
If you catch the exception, no SqlConnection will be returned. So you could return null after showing the message box.
Then of course, you will need to do a null check after calling connection() so you don't get a null reference exception trying to use it.
You also need to return the connection you are creating:
return new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|Data Directory|Coffee(LoginEmployee).mdf;Integrated Security=True;");
Note: I don't recommend hard-coding your connection string either! You would normally add the connection string to your app.config/web.config and read it using ConfigurationManager.ConnectionStrings... - this is because you might have different instance names on different machines, or you might want to point to a database on a server rather than local. You will not need to change the code and recompile just to make it work on more than one machine.
There is information on microsoft's class library site (https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnectionstringbuilder.attachdbfilename(v=vs.110).aspx) saying: An error will be generated if a log file exists in the same directory as the data file and the 'database' keyword is used when attaching the primary data file. In this case, remove the log file. Once the database is attached, a new log file will be automatically generated based on the physical path.

Adding Data to Database but get a breakpoint everytime a function is called

I am trying to write myself a Music record database program.
It works perfectly untill I try using a form to add data using input from textboxes and a button.
It generates a break point and the following error
An Unhandled exception of type 'System.ArgumentException' Occured in
System.Data.dll
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace Musicrecord
{
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
--> using(var connection = new SqlConnection("connectionString"))**
{
connection.Open();
var sql = "INSERT INTO Table(Artist, Album, Release Year) VALUES(#Artist, #Album, #Release year)";
using(var cmd = new SqlCommand(sql, connection))
{
cmd.Parameters.AddWithValue("#Artist", textBox1.Text);
cmd.Parameters.AddWithValue("#Album", textBox2.Text);
cmd.Parameters.AddWithValue("#Release Year ", textBox3.Text);
cmd.ExecuteNonQuery();
}
I haven't found after several hours of googling a solution.
If connectionString is a local variable, you need to use it as;
using(var connection = new SqlConnection(connectionString))
not
using(var connection = new SqlConnection("connectionString"))
If you use it as "connectionString", SqlConnection expects it is a valid connection string. But it is not.
Also, if your column name more than one word, you need to use it with square brackets like [Release Year]. It is the same as it's paramter name.
And don't use AddWithValue. It may generate unexpected results. Use .Add() method or it's overloads.
using(var connection = new SqlConnection(connectionString))
using(var cmd = connection.CreateCommand())
{
cmd.CommandText = "INSERT INTO Table(Artist, Album, [Release Year]) VALUES(#Artist, #Album, #ReleaseYear)";
cmd.Parameters.Add(#Artist, SqlDbType.NVarChar).Value = textBox1.Text;
cmd.Parameters.Add(#Album, SqlDbType.NVarChar).Value = textBox2.Text;
cmd.Parameters.Add(#ReleaseYear, SqlDbType.NVarChar).Value = textBox3.Text;
connection.Open();
cmd.ExecuteNonQuery();
}
I assumed your all data types are NVarChar. Also it is a good practice to specify size value as a third parameter in .Add() method.

mysql datareader not finding rows c#

I got a question about c# and mysql. I would like to make a very simpel login form that is connected to my local db. I got the connection to work (tested it) but i have a problem with reading my data that is returned from a select.
I'm trying to put an ID into a string so I can display it(this is just for testing). Now I have searched a lot on google and almost everyone has something like this. When I execute it doesn't give error but my sqldatareader finds nothing. In the first if I ask if it has got any rows and there are none.
What am I doing wrong? My username/password do exist in my db.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace eindwerk
{
public partial class LoginForm : Form
{
string myConnection = "Server=localhost;Database=mydb;Uid=root;Pwd=root;";
MySqlCommand cmd;
MySqlConnection connection;
public LoginForm()
{
InitializeComponent();
connection = new MySqlConnection(myConnection);
connection.Open();
}
private void loginForm_Load(object sender, EventArgs e)
{
this.Location = new Point((Screen.PrimaryScreen.WorkingArea.Width - this.Width) / 2,
(Screen.PrimaryScreen.WorkingArea.Height - this.Height) / 2);
}
private void btnLogin_Click(object sender, EventArgs e)
{
try
{
cmd = connection.CreateCommand();
cmd.CommandText = "SELECT idlogin FROM login WHERE (username='#username') AND (password='#password') LIMIT 1;";
cmd.Parameters.AddWithValue("#username", txtbxLoginUsername.Text);
cmd.Parameters.AddWithValue("#password", txtbxLoginPassword.Text);
MySqlDataReader rdr = cmd.ExecuteReader();
rdr.Read();
if (rdr.HasRows)
{
while (rdr.Read())
{
label1.Text = rdr.GetInt32("idlogin").ToString();
}
}
else
{
lblLoginError.Visible = true;
}
rdr.Close();
}
catch {
lblLoginError.Text = "Nope";
lblLoginError.Visible = true;
}
}
}
}
You are calling Read() Multiple time. Call the While(Reader.Read()) single time and check the result by if(rdr.HasRows()){} for check result is return or nothing is come in the response.
You are returning only 1 row, but you are calling Read() twice. Your row is effectively discarded before you look at your data.
After a long search i have found the problem ! In my sql query i put username='#username', there lies the problem. You can't use single quotes !!!. I removed the quotes and it works perfectly.
That is whay you get for trusthing a search result on the third page of google...
Thanks to all !

How to display data in gridview from MS Access?

I want to display information of user stored in a MS Access database. The user enters his userid and on clicking a button following function is called. But no data is being displayed. What am I doing wrong ?
System.Data.OleDb.OleDbConnection con;
System.Data.OleDb.OleDbDataAdapter da;
protected void Button1_Click(object sender, EventArgs e)
{
con = new System.Data.OleDb.OleDbConnection();
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;"
+ "Data Source=C:\\Users\\sam\\Desktop\\mydb.mdb";
con.Open();
string sql = "SELECT * From Leave where userid="+Textbox1.Text;
da = new System.Data.OleDb.OleDbDataAdapter(sql, con);
DataTable t = new DataTable();
da.Fill(t);
GridView1.DataSource = t;
con.Close();
}
You need to call GridView1.DataBind()
GridView1.DataSource = t;
GridView1.DataBind();
Just a side-note, it is good practice to wrap your connection with using
using(con = new System.Data.OleDb.OleDbConnection())
{
con = new System.Data.OleDb.OleDbConnection();
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;"
+ "Data Source=C:\\Users\\sam\\Desktop\\mydb.mdb";
con.Open();
...
...
}
This ensures your connection is properly disposed after use
You should use bind function:
protected void Button1_Click(object sender, EventArgs e)
{
con = new System.Data.OleDb.OleDbConnection();
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;"
+ "Data Source=C:\\Users\\sam\\Desktop\\mydb.mdb";
con.Open();
string sql = "SELECT * From Leave where userid="+Textbox1.Text;
da = new System.Data.OleDb.OleDbDataAdapter(sql, con);
DataTable t = new DataTable();
da.Fill(t);
GridView1.DataSource = t;
GridView1.DataBind();
con.Close();
}
First off, please, please please don't concatenate your WHERE parameters in your SQL. Use Parameters. Second, Add a "using System.Data.OleDb" statement at the top of your module, so that you are not having to type things like:
System.Data.OleDb.OleDbDataAdapter
Over and over again.
Try the following code. Personally, when I have to work with data tables and such, I prefer to avoid all the DataAdapter nonsense, and keep it as simple as possible.
Note in the code below:
the "using" blocks. These place the variables created within them inside their own scope, and take care of disposal and such for you.
I used an OleDb Parameter instead of concatenating criteria. This is a much safer way to do things, and creates much cleaner and more readable code as well, especially in cases where you have several criteria in your WHERE clause.
I assume your UserID input is a string, since you are grabbing the value from a Textbox. If it is in fact an int value (such as an auto-incrementing id in MS Access) you will need to use an int data type instead. You may have to mess with it a little. When you are still figuring this stuff out, it can be a bit painful. However, using parameters increases security and maintainability.
Once you have obtained a data table as the return from the MyUsers method, you should be able to simply set the data source of your Gridview. If you have difficulties still, do as Steve suggests and check the Autogenerate columns property in the designer, or set it in code.
Not that I have moved the connection string to the project Properties/Settings. You should find this in the solution designer. Place your connection string there, in one spot, and you can obtain it from anywhere in your code. If you later change the connection string (such as moving your Db to another computer, server share, etc) you need only change it in one place.
SAMPLE CODE:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb; // put this here, and stop writing long namespaces inline
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// Where possible, move code out of specific event handlers
// into methods which can be re-used from other client code.
// Here, I pulled the actual data access out into separate methods,
// and simply call it from the event handler:
this.LoadGridView(textBox1.Text);
}
private void LoadGridView(string UserID)
{
// Now we can load the gridview from other places in our
// code if needed:
this.dataGridView1.DataSource = this.MyUsers(UserID);
}
private DataTable MyUsers(string UserID)
{
var dt = new DataTable();
// Use a SQL Paramenter instead of concatenating criteria:
string SQL = "SELECT * FROM Leave WHERE userid = #UserID";
// The "using" statement limits the scope of the connection and command variables, and handles disposal
// of resources. Also note, the connection string is obtained from the project properties file:
using(OleDbConnection cn = new OleDbConnection(Properties.Settings.Default.MyConnectionString))
{
using (var cmd = new OleDbCommand(SQL, cn))
{
// For simpler things, you can use the "AddWithValue" method to initialize a new parameter,
// add it to the Parameters collection of the OleDBCommand object, and set the value:
cmd.Parameters.AddWithValue("#UserID", UserID);
// Get in, get out, get done:
cn.Open();
dt.Load(cmd.ExecuteReader());
cn.Close();
}
}
return dt;
}
}
}
Hope that helps. It's not how everyone might do it, but I have found it provides maximum flexibility, when you must work with MS Access.

How to connect to an Access database using the OleDb namespace in .NET?

I want to use an Access database for my Windows Forms application. (written with C#)
I have used OleDb namespace for connecting, and I'm able to select the records from the source using the OleDbConnection and ExecuteReader objects.
However, I can't insert, update or delete records yet.
My code is the following:
OleDbConnection con = new OleDbConnection(strCon);
try
{
string con="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=xyz.mdb;Persist Security Info=True";
con.Open();
OleDbCommand com = new OleDbCommand("INSERT INTO DPMaster(DPID, DPName, ClientID, ClientName) VALUES('53', 'we', '41', 'aw')", con);
int a = com.ExecuteNonQuery();
//OleDbCommand com = new OleDbCommand("SELECT * FROM DPMaster", con);
//OleDbDataReader dr = com.ExecuteReader();
//while (dr.Read())
//{
// MessageBox.Show(dr[2].ToString());
//}
MessageBox.Show(a.ToString());
}
catch
{
MessageBox.Show("cannot");
}
If I the commentted block is executed, the application works fine. But the insert block doesn't.
Knowing this, why I am unable to insert, update or delete database records?
the problem that I encountered myself is as:
You've added the mdb file to your solution and every time you run the program it will be copied into debug folder.
So you can select from it but deleting rows doesn't affect the original file you have in your solution.
Check for it.
First, never strangle your exception. It is better to let your exception bubble up so that you may get important information regarding what is not working properly. It is better to write:
con.Open();
OleDbCommand com = new OleDbCommand("INSERT INTO DPMaster(DPID,DPName,ClientID,ClientName) VALUES('53','we','41','aw')", con);
int a = com.ExecuteNonQuery();
than
try {
con.Open();
OleDbCommand com = new OleDbCommand("INSERT INTO DPMaster(DPID,DPName,ClientID,ClientName) VALUES('53','we','41','aw')", con);
int a=com.ExecuteNonQuery();
} catch {
MessageBox.Show("cannot");
}
Second, make use of using blocks as much as possible, since those blocks will dispose the no longer needed objects. So your code should look like this:
using (OleDbConnection con = new OleDbConnection(conStr))
using (OleDbCommand com = new OleDbCommand("INSERT INTO DPMaster(DPID,DPName,ClientID,ClientName) VALUES('53','we','41','aw')", con) {
con.Open();
int a = com.ExecuteNonQuery();
MessageBox.Show(a.ToString());
}
With this code, you will more likely get to know what is going wrong while the exception will bubble up, plus, as soon as you'll quit the scope of the using blocks, resources used will be freed up as your objects will get disposed.

Categories