How to insert data into local database using C# - c#

I am working on my first project using local database on C#. I have searched on internet different code for inserting data, but nothing has worked for me. I am trying different code, the problem that occurs to me is the built in functions they are using doesn't show up in my code. Can someone share the authentic code for inserting, retrieving and deleting in local database ?
The recent code that I have tried, some exception is occurring in SqlCeConnection.
This is my code :
string str="Data Source=(localdb)shop_database;Initial Catalog=shop_database;Integrated Security=True";
SqlCeConnection con = new SqlCeConnection(str);
SqlCeDataAdapter sda = new SqlCeDataAdapter();
SqlCeCommand cmd = con.CreateCommand();
cmd.CommandText = "Insert into Account_details (Account_No,Customer_name,Customer_father_name,Profession,Mobile_No,Office_Address,House_Address,CNIC,Item_name,Item_color,Item_model,Item_engine_NO,Item_chasis_NO,Cash_price,Installment_price,Advance_given,Amount_left,Monthly_Installment,Monthly_Rent,Date_of_giving,Sponsor_name,Sponsor_father_name,Sponsor_profession,Sponsor_Address,Sponsor_CNIC,Sponsor_Mobile_No) values (#Account_No,#Customer_name,#Customer_father_name,#Profession,#Mobile_No,#Office_Address,#House_Address,#CNIC,#Item_name,#Item_color,#Item_model,#Item_engine_NO,#Item_chasis_NO,#Cash_price,#Installment_price,#Advance_given,#Amount_left,#Monthly_Installment,#Monthly_Rent,#Date_of_giving,#Sponsor_name,#Sponsor_father_name,#Sponsor_profession,#Sponsor_Address,#Sponsor_CNIC,#Sponsor_Mobile_No)";
cmd.Parameters.AddWithValue("#Account_No", this.Textbox0.Text);
cmd.Parameters.AddWithValue("#Customer_name", this.Textbox1.Text);
cmd.Parameters.AddWithValue("#Customer_father_name", this.Textbox2.Text);
cmd.Parameters.AddWithValue("#Profession", this.Textbox3.Text);
cmd.Parameters.AddWithValue("#Mobile_No", this.Textbox4.Text);
cmd.Parameters.AddWithValue("#Office_Address", this.Textbox5.Text);
cmd.Parameters.AddWithValue("#House_Address", this.Textbox6.Text);
cmd.Parameters.AddWithValue("#CNIC", this.Textbox7.Text);
cmd.Parameters.AddWithValue("#Item_name", this.Textbox14.Text);
cmd.Parameters.AddWithValue("#Item_color", this.Textbox15.Text);
cmd.Parameters.AddWithValue("#Item_model", this.Textbox16.Text);
cmd.Parameters.AddWithValue("#Item_engine_NO", this.Textbox17.Text);
cmd.Parameters.AddWithValue("#Item_chasis_NO", this.Textbox18.Text);
cmd.Parameters.AddWithValue("#Cash_price", this.Textbox19.Text);
cmd.Parameters.AddWithValue("#Installment_price", this.Textbox20.Text);
cmd.Parameters.AddWithValue("#Advance_given", this.Textbox21.Text);
cmd.Parameters.AddWithValue("#Amount_left", this.Textbox25.Text);
cmd.Parameters.AddWithValue("#Monthly_Installment", this.Textbox22.Text);
cmd.Parameters.AddWithValue("#Monthly_Rent", this.Textbox23.Text);
cmd.Parameters.AddWithValue("#Date_of_giving", this.Textbox24.Text);
cmd.Parameters.AddWithValue("#Sponsor_name", this.Textbox8.Text);
cmd.Parameters.AddWithValue("#Sponsor_father_name", this.Textbox9.Text);
cmd.Parameters.AddWithValue("#Sponsor_profession", this.Textbox10.Text);
cmd.Parameters.AddWithValue("#Sponsor_Address", this.Textbox11.Text);
cmd.Parameters.AddWithValue("#Sponsor_CNIC", this.Textbox12.Text);
cmd.Parameters.AddWithValue("#Sponsor_Mobile_No", this.Textbox13.Text);
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("Successfully saved");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

To edit, insert, in general interact with your database you need the class SqlCommand. First you create a connection to your database with an SqlConnection object. Then you pass the SQL statement as a string and the connection into the constructor of the SqlConnection class. Little example:
SqlConnection con = new SqlConnection("server=localhost;database=test_db;uid=root;password=yourpassword");
SqlCommand cmd = new SqlCommand("select * from your_table", con);
To retreive the data from the database you need to use the SQL Statements. For example an SQL statement is something like:
insert into my_table (value1, value2)
values("Example", "Insertion");
When you created your SqlConnection and the SqlCommand you need to open the database connection and execute the command. Wether it's a command for receiving information from the database or editing the database you use ExecuteReader() or ExecuteNonQuery(). For example when you want to receive all the Information stored in one table you use:
SqlConnection con = new SqlConnection("connection string as shown above");
SqlCommand cmd = new SqlCommand("select * from example_table", con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while(reader.Read())
Console.WriteLine(reader[<table_index or attribute Name>]);
And finally dont forget to call the close method on your SqlConnection and SqlDataReader object

You are probably making two mistakes:
Problem 1. Your connecting string looks like wrong. Instead of:
Data Source=(localdb)shop_database;Initial Catalog=shop_database;Integrated Security=True";
It should be:
Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=shop_database;Integrated Security=True";
Problem 2. You are not opening the connection before executing the command. Your code in the block should be like this:
try
{
conn.Open(); // Open the connection
cmd.ExecuteNonQuery();
MessageBox.Show("Successfully saved");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close(); // Close the connection
}
As a best practice, I recommend that you use "using" block to create your connection. In that case, you don't have to explicitly close the connection and set it to null:
try
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
conn.Open();
// Remaining code
}
}
catch(Exception ex)
{
// Manage your exception here
}

Related

Cant read from SQL Server database in C#

I am currently working on a college assignment in which I am having trouble reading data from a SQL Server database. I'm attempting to read the Dentist Name column and then add these names to a combobox.
However when I input the column name it shows an error.
My table is called dentistInfo with columns Dentist ID, Dentist Name, Dentist Surname, DOB and Gender.
Eventually when I get to the reading done correctly I will then hopefully be able to populate their details when the names are selected from the combobox.
public partial class Dentist_Info : Form
{
Surgery mySurgery = new Surgery();
private SqlConnection conn;
private SqlCommand cmd;
private SqlDataAdapter da;
Surgery _formsSurgery;
public Dentist_Info(Surgery SurgeryToDisplay)
{
_formsSurgery = SurgeryToDisplay;
}
public void FillCombo()
{
SqlConnection conn = new SqlConnection(#"Data Source = GGJG; Initial Catalog = DentistDB; Integrated Security = True");
SqlCommand SelectCommand = new SqlCommand("SELECT * FROM DentistInfo", conn);
SqlDataReader myreader;
conn.Open();
try
{
myreader = SelectCommand.ExecuteReader();
while (myreader.Read())
{
string dname = myreader.GetString("Dentist Name");
comboBox1.Items.Add(dname);
}
conn.Close();
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
finally
{
if (conn != null)
{
conn.Close();
}
}
}
Pro-tip: If you want to ask about an error, post the error.
In any case, the problem is easy to spot in this case. There's no overload of GetString that accepts a string as an argument - you can only use the column index.
So either you need to pass the column index (myreader.GetOrdinal("Dentist Name")) or you need to use the indexer ((string)myreader["Dentist Name"]). In either case, make sure to handle possible NULL values properly - data reader simply throws an exception if you try to read an SQL NULL value.
As an aside, your try...catch can be simplified (and more useful):
When you want to rethrow an exception, use throw; (no "argument"). Wrap the exception only if you have some information to add.
The catch clause isn't required. It seems that you're only using it for the finally - it's perfectly fine to just use try...finally without the catch.
conn can never be null in the finally clause - your try isn't long enough.
For a pattern like this, you want to use using instead of try...finally anyway. You should also use using for the data reader.
Try this: I recommend you putting [] in the Dentist Name since it has a space between the two words, which might cause you the error, or change the name from the Database to DentistName
public void FillCombo()
{
SqlConnection conn = new SqlConnection(#"Data Source = GGJG; Initial Catalog = DentistDB; Integrated Security = True");
SqlCommand SelectCommand = new SqlCommand("SELECT * FROM DentistInfo", conn);
conn.Open();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(SelectCommand);
da.fill(ds);
foreach(DataRow dr in ds.Tables[0].Rows)
{
comboBox1.Items.Add(dr["[Dentist Name]"].ToString());
}
conn.Close();
}
As per addition instead of using conn.Open() and conn.Close(), as the answer of the first user you can surround the connection inside a using like so:
using(SqlConnection conn = new SqlConnection(#"Data Source = GGJG; Initial Catalog = DentistDB; Integrated Security = True"))
{
//your codes here no need for conn.Open() and conn.Close()
}

C# :error There is already an open DataReader associated with this Command which must be closed first

I used to call several functions with this connection string:
class Solders_DB
{
SqlConnection connection;
SqlCommand query;
String command;
public Solders_DB()
{
connection = new SqlConnection();
connection.ConnectionString = "Server=localhost;Database=Scheduling_Employee ;Trusted_Connection=True;MultipleActiveResultSets=True;";
query = new SqlCommand();
}
As you see I used this MultipleActiveResultSets=True; in my connection but in this function :
command = #"SELECT [GID] FROM [Scheduling_Employee].[dbo].[Solder] where [ID]=#ID";
query.CommandText = command;
query.Parameters.Clear();
query.Parameters.AddWithValue("#ID", id);
Object o= query.ExecuteScalar();
I faced with this error:
There is already an open datareader associated with this command which must be closed first
The code in your question is not complete. Please explain yourself better for further assistance.
When using a SqlConnection is recommended to use the 'using' statement like this:
using (SqlConnection SqlConn = new SqlConnection(ConnString))
{
try
{
SqlConn.Open();
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
return null;
}
}
You're trying to read data from the first execution of your query, please update your question and put the complete code and the error stack.
Its usually when there was another query before that one and has not yet stopped executing inside the database engine (maybe it was a heavy script). You could try query = new SqlCommand();, query.Cancel() or
while(query.Connection.State != System.Data.ConnectionState.Open){ Threading.Sleep(100);}

Cannot add data into database in visual c#

As a beginner to c#, and I actaully spent a lot of time researching this:
I cannot add some data into the database, I can extract data from it, but cannot add anything into the database. I use sql server as my database.
try {
fname = fname_tb.Text;// first name
sname = sname_tb.Text; // second name
q = "insert into beforebath1(firstname,secondname) values(#fname,#sname)";
conn_string = Properties.Settings.Default.beforebath_connection_string;
SqlConnection co = new SqlConnection(conn_string);
SqlCommand cmd;
co.Open();
cmd = new SqlCommand(q, co);
cmd.Connection = co;
cmd.Parameters.AddWithValue("#fname", fname_tb.Text);
cmd.Parameters.AddWithValue("#sname", sname_tb.Text);
cmd.ExecuteNonQuery();
co.Close();
}
catch(Exception err) {
MessageBox.Show(err.toString());
}
my sql connection string is this:
Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\beforebath_db.mdf;Integrated Security=True;Connect Timeout=30
It is automatically generated when I created the database. Please help me insert the text in the two textboxes (fname_tb.Text and sname_tb.Text) into the table called beforebath1 of the database called beforebath_db.mdf.
Is it something to do with my data directory?
I see a couple of mistakes in your code.
First, why catch an exception that will only be shown in a message?
It is often best to let the exception bubble up to have the stack trace in debug. This is not the same if this is production code, which I doubt.
Second, make sure to dispose your objects adequately.
The Using Statement is the most prefered way to work with disposeable items such as a database connection and a command.
using (var cnx = new SqlConnection(connectionString)) {
cnx.Open();
var sql = #"insert into beforebath1 (first_name, second_name)
values (#fname, #lname)";
using (var cmd = new SqlCommand(sql, cnx)) {
cmd.Parameters.AddWithValue("#fname", fname_tb.Text);
cmd.Parameters.AddWithValue("#lname", lname_tb.Text);
try {
int rowsAffected = cmd.ExecuteNonQuery();
if (0 < rowsAffected) MessageBox.Show("Success!");
else MessageBox.Show("Failed!");
} catch (SqlException ex) {
// It is almost prefered to let the exception be thrown freely
// so that you may have its full stack trace and have more
// details on your error.
MessageBox.Show(ex.Message);
} finally {
if (cnx.State == ConnectionState.Open) cnx.Close();
}
}
}
This way, wrapping your disposable objects within using blocks, you make sure that everything is getting to get disposed automatically when exiting the code block.
As for your "it doesn't work" problem, I guess the problem be either at the connection string level, or at your table_name level.
You wish to insert into beforebath1, and your insert statement states table_name. Make sure you put the right table name where it belongs so that it may work properly.
Can you change you connection string to this:
Server=(LocalDB)\v11.0;Database=beforebath_db;Trusted_Connection=True;
This means the your app and other programs using the Db will all share the same instance.
Also, as mentioned by #Will, you should wrap your SQLConnection in a using statement for garbage collection.
For better implementations you can use stored_procedures like bellow:
Step1: Declare Stored Procedure for your Query:
CREATE PROCEDURE [dbo].[ADD_TO_BEFORE_PATH_SP]
/*Type of this variables should be their column types*/
#fname varchar(MAX),
#lname varchar(MAX)
AS
BEGIN
INSERT INTO [dbo].[beforebath1] (fname, lname)
VALUES (#fname,#lname)
END
Step2: Using Stored Procedure where you need:
SqlConnection con = new SqlConnection(connectionString);
SqlCommand com = new SqlCommand("ADD_TO_BEFORE_PATH_SP", con);
com.Parameters.AddWithValue("#fname", fname_tb.Text);
com.Parameters.AddWithValue("#lname", lname_tb.Text);
com.CommandType = CommandType.StoredProcedure;
try
{
con.Open();
com.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
if (con.State == ConnectionState.Open)
con.Close();
}

C# Oracle connection string for DataGrid

When I import Dataset to application in connnection string I choose "No exclude information from connection string. I will set this information in my aplication".
Now when I compile the form there is nothing to see in the DataGrid, where I must place connection in my application to connet ?
Now I have:
public Form1()
{
InitializeComponent();
using (OracleConnection con = new OracleConnection("Data Source=localhost;Persist Security Info=True;User ID=martynas;Password=xxxxxxx;Unicode=True"))
{
try
{
con.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = con;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
This conection is open, but DataGridView still does not show any records. I think that maybe I place connection in wrong method ?
You are not connecting your OracleCommand to anything. You create it but when it goes out of scope, it ceases to exists.

Is it possible to reuse a connection when accessing multiple tables in C#?

I am new to C#. I have a program which reads multiple tables in single database. Suppose if i am reading table A so before reading this I have to connect to database in C#. after this I have to fetch some information from table B. Do I have to give the server info, userid and password again to connect to database?
You can use a single connection for both tables as long as the user has permissions to read from table A and table B.
For example, if you're using SqlCommands and a SqlConnection, set the connection as follows:
SqlConnection connection;
SqlCommand commandA;
SqlCommand commandB;
connection = new SqlConnection("some connection string");
connection.Open();
commandA = new SqlCommand();
commandA.Connection = connection;
commandB = new SqlCommand();
commandB.Connection = connection;
You can then set the CommandType and CommandText on both commandA and commandB as needed. As long as the connection is still open and the user has access to both tables, you'll be set.
We would need to see your code (please mask out your actual user credentials) but the short answer will be yes if you are using a seperate connection to perform the fetch.
If your SqlConnection object has not been disposed or closed you can reuse it on your next SqlCommand
Yes you can. SqlConnection implements IDisposible, so wrap it in a using block.
Psuedocode:
try
{
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
conn.Open();
SqlCommand comm = new SqlCommand(conn);
comm.CommandText = "Select Col1, Col2 From Table1";
SqlCommand comm1 = new SqlCommand(conn);
comm.CommentText = "Select Col1, Col2 From Table2";
//Execute First Command Code
//Execute Second Command Code
} //Connection will be closed and disposed
}
catch (Exception e)
{
//Handle e - Really want to handle specific types of exceptions, like SqlExceptions etc.
}

Categories

Resources