How to properly store data into database - c#

I'm facing a very simple problem, but I don't know how to solve it. I have a simple textBox, and local database, Database1.mdf, with one table: emp. Inserting data works fine, but when I restart application, then these data are lost.
I'm also using a dataSet, where I can see data in the table - the record is properly inserted, but it is lost when I restart the app. What am I missing?
I'm running a C# application (VS2013):
private void button1_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection(global::base.Properties.Settings.Default.Database1ConnectionString);
try {
string sql = "INSERT INTO emp (name) VALUES ('" + textBox1.Text + "')";
SqlCommand exesql = new SqlCommand(sql, cn);
cn.Open();
exesql.ExecuteNonQuery();
MessageBox.Show("Hooray!!");
this.empTableAdapter.Fill(this.database1DataSet.emp);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
cn.Close();
}
}

Set Database1.mdf's "Copy to Output Directory" property value to "Do not copy" from Properties box.

Related

Connection String Not Working- Not Allowing Connection to Database made in VS (C# Visual Studio)

I am currently working on building an attendance tracker that will take the user's input data and add it to a database table. I'm running into an issue where my connection string will not connect to the database? I've copied it directly as is, and even tried a few different tutorials with alternative ways with no success. This is for an assignment however, our SQL portion was quite small and I'm not sure where to go from here. Please let me know if something in my code needs revisited.
When I run the code I get the "unable to connect" exception I created below. I need it to run and add the user input to the table.
I have also noticed that my database connection often disconnects unless I refresh, is this common?
namespace AttendanceTracker
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void signInButton_Click(object sender, EventArgs e)
{
string connectionString = null;
connectionString = #"Data Source=(LocalDB)\MSSQLLocalDB; AttachDbFilename = C:\Users\soupy\Desktop\AttendanceTracker\AttendanceTrackerDatabase.mdf; Integrated Security = SSPI";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = ("INSERT into AttendanceTrackerDatabase VALUES (#studentName,#studentID,#Date,#class)");
cmd.Parameters.AddWithValue("#Student_Name", nameTextBox.Text);
cmd.Parameters.AddWithValue("#Student_ID", studentIDTextBox.Text);
cmd.Parameters.AddWithValue("#Class", classDropDown.Text);
cmd.Parameters.AddWithValue("#Date", attendanceDate.Value);
try
{
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Your sign in has been recorded successfully!");
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("Unable to open attendance tracker for updating.");
}
}
When using Parameter objects, you should ensure that the variable names are consistent.
Please modify your code as follows
cmd.CommandText = ("INSERT into AttendanceTrackerDatabase VALUES (#studentName,#studentID,#Date,#class)");
cmd.Parameters.AddWithValue("#studentName", nameTextBox.Text); // Modified to "studentName"
cmd.Parameters.AddWithValue("#studentID", studentIDTextBox.Text); // Modified to "studentID"
cmd.Parameters.AddWithValue("#Date", attendanceDate.Value);
cmd.Parameters.AddWithValue("#class", classDropDown.Text); // Modified to "class"

Store A List Of Data In Mysql DataBase?

i have a list of String Data i would Like to Store in my MySQL database Table in Column "Categories".
Is there a way to store it at a go because its a long list.`
public Class PickerView{
List<string> CategoriesPicker = new List<string>();
public Button SaveItemsButton = new Button();
public PickerView()
{
CategoriesPicker.Items.Add("Hotels & Travel");
CategoriesPicker.Items.Add("Restaurant");
CategoriesPicker.Items.Add("Wholesalers");
CategoriesPicker.Items.Add("Automotives");
CategoriesPicker.Items.Add("Pets");
CategoriesPicker.Items.Add("Musical Instruments Services");
CategoriesPicker.Items.Add("Specialty Food");
CategoriesPicker.Items.Add("Food");
CategoriesPicker.Items.Add("Boutique");
CategoriesPicker.Items.Add("Home & Gardens");
CategoriesPicker.Items.Add("Shopping");
CategoriesPicker.Items.Add("Education");
CategoriesPicker.Items.Add("Books,Mags,Music & Video");
CategoriesPicker.Items.Add("Fashion");
CategoriesPicker.Items.Add("Event Planning & Services");
CategoriesPicker.Items.Add("Arts & Craft");
CategoriesPicker.Items.Add("Local Services");
CategoriesPicker.Items.Add("NightLife(Bars..)");
SaveItemsButton.Clicked += SavedItemsButton_Clicked
}
private void SavedItemsButton_Clicked(object sender, System.EventArgs e)
{
string sqlstring = "server=; port= ; user id =;Password= ;Database=test;";
MySqlConnection conn = new MySqlConnection(sqlstring);
try
{
conn.Open();
}
catch (MySqlException ex)
{
throw ex;
}
string Query = "INSERT INTO test.maintable (Categories)values('" +(**//I DONT KNOW WHAT TO WRITE HERE TO SAVE ALL AT ONCE**) + "');";
MySqlCommand cmd = new MySqlCommand(Query, conn);
cmd.ExecuteReader();
conn.Close();
}
}`
How do i save the list of items in CategoriesPicker in database when SaveItemsButton is clicked.
Simple use the mysql insert into statement.
insert into tbl1 values
(1, 'Name1', 1, null),
(2, 'Name2', 2, null),
(3, 'Name3', 1, null);
(3, 'Name3', 1, null) is of course the structure of tbl1
This will work in any language you use or even in comand line
MySQL (and MariaDB) don't have list-valued column types since that goes against first normal form in database design.
What you do instead is what #nbk suggested and, using whatever database framework you chose, insert multiple rows. Here's a sample table definition for MariaDB/MySQL if you don't have one already:
Microsoft's current recommended way of interacting with a database is Entity Framework Core. The documentation there can help you with connecting to a database, creating a table, adding rows to a table and saving all of that to the database.
Hope that helps!
I added using blocks to your code to ensure that your database objects are closed and disposed even if there is an error.
Set the query text only once, it stays the same for each iteration of the loop. Likewise the parameter is added outside the loop. Only the value of the parameter is changed inside the loop. We use .ExecuteNonQuery (not reader) for Insert, Update or Delete. .ExecuteReader is used for returning data.
private List<string> CategoriesPicker = new List<string>();
//add all the items to the list
private void SavedItemsButton_Clicked(object sender, System.EventArgs e)
{
string sqlstring = "server=; port= ; user id =;Password= ;Database=test;";
using (MySqlConnection conn = new MySqlConnection(sqlstring))
{
string Query = "INSERT INTO test.maintable (Categories)values(#Category);";
using (MySqlCommand cmd = new MySqlCommand(Query, conn))
{
cmd.Parameters.Add("#Category", MySqlDbType.VarChar);
try
{
conn.Open();
}
catch (MySqlException ex)
{
throw ex;
}
foreach (String item in CategoriesPicker)
{
cmd.Parameters["#Category"].Value = item;
cmd.ExecuteNonQuery();
}
}
}
}

how to connect sql database server to usercontrol in windowsform by using c#?

I tried to connect the database to the user control that has in my desktop application. the catch block is running. can anyone see any error in here?
can someone help to find the correct code to connect SQL server management studio 2014 to windows form Application?
I have tried the code as we use to windows form. but it isn't working .is there any different code that uses to user control database connection?
SqlCommand cmd;
SqlConnection con;
private void btnsave_Click(object sender, EventArgs e) {
try {
con = new SqlConnection(# "Data Source=LAPTOP-EN6B5ABV;Initial Catalog=nature;Integrated Security=True");
con.Open();
cmd = new SqlCommand("INSERT INTO crop" + " (cropid, cropname, scnname, noofplant, culdate, ferttimeperiod, harvetimeperiod, addeddate,lifetime,lifetimeperiod) VALUES (#cropid, #cropname, #scnname, #noofplant, #culdate, #ferttimeperiod, #harvetimeperiod, #addeddate,#lifetime,#lifetimeperiod)", con);
cmd.Parameters.AddWithValue("#cropid", txtcropid.Text);
cmd.Parameters.AddWithValue("#cropname", txtcropname.Text);
cmd.Parameters.AddWithValue("#scnname", txtscnname.Text);
cmd.Parameters.AddWithValue("#noofplant", textBox1.Text);
cmd.Parameters.AddWithValue("#culdate", dateTimePicker1.Text);
cmd.Parameters.AddWithValue("#ferttimeperiod", comfert.SelectedItem);
cmd.Parameters.AddWithValue("#harvetimeperiod", comboBox1.SelectedItem);
cmd.Parameters.AddWithValue("#lifetime", textBox2.Text);
cmd.Parameters.AddWithValue("#lifetimeperiod", combolifetime.SelectedItem);
cmd.Parameters.AddWithValue("#addeddate", addeddate.Text);
cmd.ExecuteNonQuery();
con.Close();
} catch (Exception) {
MessageBox.Show("something went wrong in database server");
}
I expect the insertion of the data.
Here is my code that I got the correct output. There was an error related to the datetimepicker value. When Get the selected value of datetimepicker it was given an error.
I used this statement to insert date to the database.
cmd.Parameters.AddWithValue("#culdate", Convert.ToDateTime(dateTimePicker1.Value));
string date =DateTime.Now.ToShortDateString();
cmd.Parameters.AddWithValue("#cropid", txtcropid.Text);
cmd.Parameters.AddWithValue("#cropname", txtcropname.Text);
cmd.Parameters.AddWithValue("#scnname", txtscnname.Text);
cmd.Parameters.AddWithValue("#noofplant", txtnoofplant.Text);
cmd.Parameters.AddWithValue("#culdate", Convert.ToDateTime(dateTimePicker1.Value));
cmd.Parameters.AddWithValue("#ferttimeperiod", txtharvtime.Text);
cmd.Parameters.AddWithValue("#fert", comfert.SelectedItem.ToString());
cmd.Parameters.AddWithValue("#harvtimeperiod", txtharvtime.Text);
cmd.Parameters.AddWithValue("#harv", comboBox1.SelectedItem.ToString());
cmd.Parameters.AddWithValue("#addeddate", date);
cmd.Parameters.AddWithValue("#lifetimeperiod", txtlifetime.Text);
cmd.Parameters.AddWithValue("#life", combolifetime.SelectedItem.ToString());
cmd.ExecuteNonQuery();
con.Close();
string msg = "Crop Details are successfully saved...";
string title = "Saved";
System.Media.SystemSounds.Asterisk.Play();
MessageBox.Show(msg, title, MessageBoxButtons.OK, MessageBoxIcon.None);

MSAccess database update not updating using c#

I am making a database system. I've implemented the INSERT function properly but when I tried implementing the UPDATE function, I couldn't make any changes to the database. I don;t know where I went wrong.
Note: username is declared as string
Here is the function handling the UPDATE:
private void btnUpdate_Click(object sender, EventArgs e)
{
string q = "UPDATE [registrationinfo] SET [Password]='?', [EmailAdd]='?', [HomeAdd]='?' WHERE [Username]='?'";
OleDbConnection connect = new OleDbConnection(MyConnectionString);
connect.Open();
try
{
OleDbCommand command = new OleDbCommand(q,connect);
command.Parameters.AddWithValue("#Password", txt_password.Text);
command.Parameters.AddWithValue("#EmailAdd", txt_eadd.Text);
command.Parameters.AddWithValue("#HomeAdd", txt_homeadd.Text);
command.Parameters.AddWithValue("Username", username);
command.ExecuteNonQuery();
txt_password.Clear();
txt_eadd.Clear();
txt_homeadd.Clear();
txt_conPass.Clear();
}
catch (Exception ex)
{
connect.Close();
MessageBox.Show(ex.Message.ToString());
}
connect.Close();
}
When using a parameterized query you do not need to put single quotes (') around text parameters in your CommandText, so you should be using something like this:
string q = "UPDATE [registrationinfo] SET [Password]=?, [EmailAdd]=?, [HomeAdd]=? WHERE [Username]=?";

SQL server express, cannot read or write in C#

I have a code written that automatically adds and reads information from my SQL Server 2012 Express table, Logins. But it wont work, here is the code:
private void Form1_Load(object sender, EventArgs e)
{
SqlConnection myConnection = new SqlConnection("user id=myComputer;" + "server=MYCOMPUTER-PC\\SQLEXPRESS;" +
"Trusted_Connection=yes;" + "database=loginTest; " + "connection timeout=5");
try
{
myConnection.Open();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
SqlCommand myCommand = new SqlCommand("INSERT INTO dbo.Logins Values ('John','Password','Admin')", myConnection);
try
{
SqlDataReader myReader = null;
SqlCommand myCommand1 = new SqlCommand("select * from Logins",
myConnection);
myReader = myCommand1.ExecuteReader();
while (myReader.Read())
{
MessageBox.Show(myReader["Column1"].ToString());
MessageBox.Show(myReader["Column2"].ToString());
}
}
catch (Exception ex1)
{
MessageBox.Show(ex1.ToString());
}
}
I have debugged the program and it all seems to go through fine, it skips over :
{
MessageBox.Show(myReader["Column1"].ToString());
MessageBox.Show(myReader["Column2"].ToString());
}
for some reason, and it doesnt write the values i told it to.
Can anyone tell me why? Im a beginner at SQL, so go easy please :)
PS It doesnt fire out any error codes or exceptions
You Logins table doesn't have any records, if you mean you want to try inserting some record first to test, it's this line causing your problem:
SqlCommand myCommand = new SqlCommand("INSERT INTO dbo.Logins Values ('John','Password','Admin')", myConnection);
myCommand.ExecuteNonQuery();//Do this to insert something into your Logins first.
it skips over [...]
Presumably that's because there's no data to read, so myReader.Read() just returns false.
it doesnt write the values i told it to.
You don't actually tell it to write anything. You create a SqlCommand to insert data, but you never execute it. You need to use myCommand.ExecuteNonQuery. You should also use using statements for the commands, the connection and the reader, to make sure they get closed properly.

Categories

Resources