C# Insert with MS Access not inserting? - c#

I'm trying to insert new rows to an Access database in C#. The code compiles and supposedly inserts new data to the database, but there is no new data after the datagridview update. Also no new data on the database itself.
Sorry, I'm new with this, could someone help me?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Data.OleDb;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplicaction1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
OleDbConnection connect = new OleDbConnection();
private void Form1_Load(object sender, EventArgs e)
{
this.articulosTableAdapter.Fill(this.inventarioDataSet.Articulos);
}
private void UpdateTable()
{
connect.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Kudox\Desktop\Inventario.accdb";
connect.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connect;
string query = "SELECT * from Articulos";
command.CommandText = query;
OleDbDataAdapter da = new OleDbDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
connect.Close();
}
private void btnInsertar_Click(object sender, EventArgs e)
{
connect.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Kudox\Desktop\Inventario.accdb";
string Nombre;
int Cantidad, CostoPU, Importancia, CostoTO;
try
{
Nombre = txtNombre.Text;
Cantidad = int.Parse(txtCantidad.Text);
CostoPU = int.Parse(txtCosto.Text);
Importancia = int.Parse(cmbImportancia.SelectedItem.ToString());
CostoTO = CostoPU * Cantidad;
connect.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Kudox\Desktop\Inventario.accdb";
OleDbCommand cmd = new OleDbCommand("INSERT into Articulos(NombreArticulo, CostoPorUnidad, CantidadDeArticulos, Importancia, CostoTotal) values('"+Nombre+"','" + CostoPU +"','" + Cantidad +"','" + Importancia +"','" + CostoTO +"')");
MessageBox.Show("Articulo agregado");
UpdateTable();
}
catch(Exception err)
{
MessageBox.Show(err.Message);
}
}
}
}

After setting your datasource, you need to databind, so within your UpdateTable() procedure, after dataGridView1.DataSource = dt;, add:
dataGridView1.DataBind();
As far as your insert command, you need to execute it at some point (probably right after your OleDbCommand cmd = ... line), something like:
cmd.ExecuteNonQuery();

Related

Can't retrieve data from database and store into a value

I am currently working on a forum project using a gridview to attached the data to the database. Using SelectedIndexChanged, it will redirect to another page to display the details in labels. However, I am unable to display & there isn't any specific error.
This is my code:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class FAQViewPost : System.Web.UI.Page
{
string _connStr = ConfigurationManager.ConnectionStrings["WingsDrinksDbContext"].ConnectionString;
FAQ faq = null;
string CustQuestionCategory = null;
string CustQuestion = null;
protected void Page_Load(object sender, EventArgs e)
{
string FAQID = Request.QueryString["FAQID"].ToString();
Load(FAQID);
}
protected void Load(string FAQID)
{
DataTable dt = new DataTable();
string queryStr = "SELECT * FROM [FAQ] WHERE FAQID = #FAQID ";
SqlConnection conn = new SqlConnection(_connStr);
SqlCommand cmd = new SqlCommand();
string[] arr = { queryStr };
string allQueries = string.Join(";", arr);
cmd.CommandText = allQueries;
cmd.Connection = conn;
cmd.Parameters.AddWithValue("#FAQID", FAQID);
SqlDataAdapter sqlDa = new SqlDataAdapter(cmd);
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
lbl_category.Text = dt.Rows[0]["CustQuestionCategory"].ToString();
lbl_question.Text = dt.Rows[0]["CustQuestion"].ToString();
}
conn.Close();
conn.Dispose();
}
}
I do not know why you are putting the SQL into an array. You only have one statement. Try using just:
DataTable dt = new DataTable();
string queryStr = "SELECT * FROM [FAQ] WHERE FAQID = #FAQID ";
SqlConnection conn = new SqlConnection(_connStr);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = queryStr;
cmd.Connection = conn;
cmd.Parameters.AddWithValue("#FAQID", FAQID);
SqlDataAdapter sqlDa = new SqlDataAdapter(cmd);
sqlDa.Fill(dt);
I presume you have checked that the FAQ table has a record for the id you are sending? Also life would be a bit safer if you used numeric ids.

SQlite local Database data has gone when application restart?

I am developing windows application .Net in C#
DB stored inside the C# Application ".....\SQliteExample\SQliteExample\bin\Debug\MyDatabase.sqlite"
I can insert,update ,view and Delete to the table with the above code and view its contents in another activity with no troubles at all. However, when I restart the application I found that what I have inserted data before I restart the application has gone!
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.SQLite;
namespace SQliteExample
{
public partial class Form1 : Form
{
SQLiteConnection connection = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");
public Form1()
{
InitializeComponent();
SQLiteConnection.CreateFile("MyDatabase.sqlite");
connection.Open();
string sql = "create table Employee1 (EmpID int,EmpName varchar(20), age int,Salary int,Phone int , Address Varchar(20))";
SQLiteCommand command = new SQLiteCommand(sql, connection);
command.ExecuteNonQuery();
connection.Close();
}
private void btnSave_Click(object sender, EventArgs e)
{
if (connection.State != ConnectionState.Open)
connection.Open();
string sql1 = "insert into Employee1 (EmpID,EmpName,Age,Salary,Phone,Address) values (?,?,?,?,?,?)";
SQLiteCommand command = connection.CreateCommand();
command.CommandText = sql1;
command.Parameters.AddWithValue("EmpID", textBox1.Text);
command.Parameters.AddWithValue("EmpName", textBox2.Text);
command.Parameters.AddWithValue("Age", textBox3.Text);
command.Parameters.AddWithValue("Salary", textBox4.Text);
command.Parameters.AddWithValue("Phone", textBox5.Text);
command.Parameters.AddWithValue("Address", textBox6.Text);
command.ExecuteNonQuery();
connection.Close();
MessageBox.Show("Data Saved");
Clear();
View();
}
private void Clear()
{
textBox1.Text = string.Empty;
textBox2.Text = string.Empty;
textBox3.Text = string.Empty;
textBox4.Text = string.Empty;
textBox5.Text = string.Empty;
textBox6.Text = string.Empty;
}
private void View()
{
string sql3 = "select * from Employee1 order by EmpID asc";
SQLiteCommand command3 = new SQLiteCommand(sql3, connection);
DataTable dt = new DataTable();
SQLiteDataAdapter da = new SQLiteDataAdapter(command3);
da.Fill(dt);
dataGridView1.DataSource = dt;
connection.Close();
}
private void btnSelect_Click(object sender, EventArgs e)
{
View();
}
private void btnDelete_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(textBox1.Text))
{
if (connection.State != ConnectionState.Open)
connection.Open();
string sql1 = "delete from Employee1 where EmpID = ?";
SQLiteCommand command = connection.CreateCommand();
command.CommandText = sql1;
command.Parameters.AddWithValue("EmpID", int.Parse(textBox1.Text));
command.ExecuteNonQuery();
connection.Close();
Clear();
View();
}
else
{
MessageBox.Show("Please Enter EmpID");
}
}
}
}
Thanks in Advance,
On recompilation you recreate the database file and recreate the table "employee". Therefore all your previous data is lost.

Cant get Datatable to fill because of "da.Fill(dt);" not working. please help, for an assignment

here is my code
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.OleDb;
namespace SDD_Single_Project___Michael
{
public partial class AllData : Form
{
private OleDbConnection connection = new OleDbConnection();
public AllData()
{
InitializeComponent();
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=G:\schoolwork\Year 11\SDD\3 SINGLE TASK\SDD Single Project - Michael \SDD Single Project - Michael \bin\Persondata.accdb;
Persist Security Info=False;";
}
private void btnBack_Click(object sender, EventArgs e)
{
this.Hide(); //hides this page
MainScreen frm = new MainScreen(); //finds the next screen (the main game)
frm.Show(); //shows it
}
private void btnShow_Click(object sender, EventArgs e)
{
try
{
connection.Open(); //opens connection
OleDbCommand command = new OleDbCommand(); //declare our object of oleDB command
command.Connection = connection; // the connection is giving to the command
string query = "select * Persondata";
command.CommandText = query; // pass the query to the command
OleDbDataAdapter da = new OleDbDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt); // the error supposedly occurs here!!
dataGridView1.DataSource = dt;
connection.Close(); // closes the connection
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
}
}
the error code i get when i try running the program is that it is a syntax error at'*Persondata' on line 46 (which is theda.Fill(dt); line) and i cant figure it out. Please help its for an assignment.
This:
"select * Persondata"
must be
"select * FROM Persondata"

What is the correct syntax for establishing an SQL connection and creating SQL Commands with VS2012?

I'm not really sure where the SqlConnection, SqlCommand and the Open()/Close() goes. I want to use just the single variable cmd throughout the program, hence not using the SqlCommand cmd = new SqlCommand('SELCT * FROM blabla); format.
EDIT: My code below results to the textbox having the text "System.Data.SqlClient.SqlCommand" when i click the button.
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;
using System.Data.SqlTypes;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
SqlConnection con = new SqlConnection(#"Data Source=EDIOTH\SQLEXPRESS;
Initial Catalog=Try; Integrated Security=SSPI");
SqlCommand cmd = new SqlCommand();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
con.Open();
cmd.CommandText = "SELECT Pnt_Lname FROM PATIENT WHERE Pnt_ID = 1;";
txtBox1.Text = cmd.ToString();
con.Close();
}
}
}
you can create constant string to hold the connection string and then you can do as below in your button1_Click
you don't need to call the close method of sql connection when you use using block as below
using(SqlConnection con = new SqlConnection(connectionString))
using(SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "SELECT Pnt_Lname FROM PATIENT WHERE Pnt_ID = 1";
con.Open();
txtBox1.Text =cmd.ExecuteScalar() as string;
}
And also if you need to read Pnt_Lname from database you better use ExecuteScalar method
You can use this structure. Use using to properly close and dispose of SqlConnection.
Also, you can define the connection string in your config file and use it from there.
using (SqlConnection conn = new SqlConnection(#"Data Source=EDIOTH\SQLEXPRESS;
Initial Catalog=Try; Integrated Security=SSPI"))
{
conn.Open();
SqlCommand command = conn.CreateCommand();
command.CommandText = "SELECT Pnt_Lname FROM PATIENT WHERE Pnt_ID = 1";
txtBox1.Text = (String)command.ExecuteScalar();
}
In case this would be of help to anyone, this is the answer to my question:
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 Book
{
public partial class frmBook : Form
{
SqlConnection con =
new SqlConnection(#"Data Source=EDIOTH\SQLEXPRESS;
Initial Catalog=XXDB; Integrated Security=SSPI");
SqlCommand cmd;
public frmBook()
{
InitializeComponent();
}
private void frmBook_Load(object sender, EventArgs e)
{
con.Open();
cmd = new SqlCommand("SELECT min(Book_ID) FROM Book;",con);
txtID.Text = cmd.ExecuteScalar().ToString();
cmd = new SqlCommand("SELECT title FROM Book WHERE Book_ID = '"
+ txtID.Text + "'", con);
txtTitle.Text = cmd.ExecuteScalar().ToString();
con.Close();
btnSave.Enabled = false;
}
private void btnNext_Click(object sender, EventArgs e)
{
int count = int.Parse(txtID.Text) + 1;
con.Open();
cmd = new SqlCommand("SELECT title FROM Book WHERE Book_ID = '"
+ count.ToString() +"'", con);
txtTitle.Text = cmd.ExecuteScalar().ToString();
txtID.Text = count.ToString();
con.Close();
}
private void btnNew_Click(object sender, EventArgs e)
{
txtID.Text = "";
txtTitle.Text = "";
txtAuthor.Text = "";
btnNew.Enabled = false;
btnSave.Enabled = true;
}
private void btnSave_Click(object sender, EventArgs e)
{
con.Open();
cmd = new SqlCommand("INSERT INTO Book (Book_ID, Title, Author) " +
"VALUES ('"+ txtID.Text +
"','"+ txtTitle.Text +
"','"+ txtAuthor.Text +"');", con);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data saved!");
btnSave.Enabled = false;
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
}
}

problem getting my data from access 2003 db into c# (dbReader.GetString error)

[got a bit further so its updated]
Hello There, i really hope you are able to help me!
Now the first part of my code does work, and I do get my report numbers out in my combobox, and i'm able to write that number to a lbl. now I need to take that number and get the rest of my data from my Access 2003 database, and drop them in a string (my output). ( I dont really want all the data loaded into my mem when i open the program, so i belive only getting the [Rapport nr] until i choose one, where I will load the data into the string and save it there for now) :)
my problem is that this wont work!
output = dbReader.GetString(dbReader.GetOrdinal("Dato")).ToString();
OBS: my error is now that it says i dont have any data in my rows or coloums
my code is as follows:
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.Collections;
using System.Data.OleDb;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private string aktuelRapportNR = "";
string output = "";
private string connectionName = "Provider=Microsoft.Jet.OLEDB.4.0;"
+ "Data Source=semcqdjh-access 2007.mdb;"
+ "Jet OLEDB:Database Password=;";
public Form1()
{
InitializeComponent();
#region Indlæsning af combobox, med rapport numre
OleDbConnection Myconnection = null;
OleDbDataReader dbReader = null;
Myconnection = new OleDbConnection(connectionName);
Myconnection.Open();
OleDbCommand cmd = Myconnection.CreateCommand();
cmd.CommandText = "SELECT [Rapport nr] FROM AVR";
dbReader = cmd.ExecuteReader();
int rapportNR;
while (dbReader.Read())
{
rapportNR = (int)dbReader.GetInt32(dbReader.GetOrdinal("Rapport nr"));
comboBox1.Items.Add(rapportNR);
}
dbReader.Close();
Myconnection.Close();
#endregion
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
aktuelRapportNR = comboBox1.SelectedItem.ToString();
lblAktuelRapportNR.Text = aktuelRapportNR;
OleDbConnection Myconnection = null;
OleDbDataReader dbReader = null;
Myconnection = new OleDbConnection(connectionName);
Myconnection.Open();
OleDbCommand cmd = Myconnection.CreateCommand();
cmd.CommandText = "SELECT [Dato] FROM AVR WHERE [Rapport nr] =" + aktuelRapportNR;
dbReader = cmd.ExecuteReader();
try
{
output = dbReader.GetString(dbReader.GetOrdinal("Dato")).ToString();
}
catch (Exception)
{
output = "fejl eller tom";
}
dbReader.Close();
Myconnection.Close();
label1.Text = output;
}
private void btnExport_Click(object sender, EventArgs e)
{
}
}
}
i figured this out :D after a break i went back to this and tried to see if there where enother method i could use and there was :P i figured by the error that it was properly something about the types so insted of taking one out and trying to work around that i took the hole row out and placed it in a object array :P by using GetValues in the dbReader i got it to work, so i can now move on :D for those who might be interested! here is my code :P its not pretty but it works :P i allso took in som try catch just to make sure i check for errors and getting a friendly respons on that :)
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.Collections;
using System.Data.OleDb;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private string aktuelRapportNR = "";
string output;
private string connectionName = "Provider=Microsoft.Jet.OLEDB.4.0;"
+ "Data Source=semcqdjh-access 2007.mdb;"
+ "Jet OLEDB:Database Password=;";
public Form1()
{
InitializeComponent();
#region Indlæsning af combobox, med rapport numre
try
{
OleDbConnection Myconnection = null;
OleDbDataReader dbReader = null;
Myconnection = new OleDbConnection(connectionName);
Myconnection.Open();
OleDbCommand cmd = Myconnection.CreateCommand();
cmd.CommandText = "SELECT [Rapport nr] FROM AVR";
dbReader = cmd.ExecuteReader();
int rapportNR;
while (dbReader.Read())
{
rapportNR = (int)dbReader.GetInt32(dbReader.GetOrdinal("Rapport nr"));
comboBox1.Items.Add(rapportNR);
}
dbReader.Close();
Myconnection.Close();
txtStatus.Text = "Indlæsning Fuldført! Vælg venligst en rapport";
}
catch (Exception)
{
txtStatus.Text = "Indlæsning Fejlet!";
}
#endregion
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
aktuelRapportNR = comboBox1.SelectedItem.ToString();
lblAktuelRapportNR.Text = aktuelRapportNR;
txtStatus.Text = "Du har valgt rapport nr.: " + aktuelRapportNR + "! Klik på export";
}
private void btnExport_Click(object sender, EventArgs e)
{
try
{
OleDbConnection Myconnection = null;
OleDbDataReader dbReader = null;
Myconnection = new OleDbConnection(connectionName);
Myconnection.Open();
OleDbCommand cmd = Myconnection.CreateCommand();
cmd.CommandText = "SELECT * FROM AVR WHERE [Rapport nr] =" + aktuelRapportNR;
dbReader = cmd.ExecuteReader();
object[] liste = new object[dbReader.FieldCount];
if (dbReader.Read() == true)
{
int NumberOfColums = dbReader.GetValues(liste);
for (int i = 0; i < NumberOfColums; i++)
{
output += "|" + liste[i].ToString();
}
}
dbReader.Close();
Myconnection.Close();
txtStatus.Text = "Export Lykkes! Luk programmet!";
}
catch (Exception)
{
txtStatus.Text = "Export Fejlet!";
}
}
}
}

Categories

Resources