I am working In c# and inserting my data into an Access database. It runs properly but crashes when I try to insert data, any idea why?
public partial class StudentInfo : Form
{
private OleDbConnection myCon;
public StudentInfo()
{
InitializeComponent();
myCon = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Documents and Settings\Administrator\My Documents\Visual Studio 2008\Projects\database program\database program\Students.mdb");
}
private void InsertBtn_Click(object sender, EventArgs e)
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Insert into StudentInfo(Rollno,SName,SFather,SAdress) Values ('"+ Rollnotb.Text+"','"+nametb.Text+"','"+fathertb.Text+"','"+adresstb.Text+"')";
cmd.Connection=myCon;
myCon.Open();
cmd.ExecuteNonQuery();
myCon.Close();
}
}
The problem can be that you are inserting all fields as text values and maybe some are defined as numeric in the MS Access table (rollNo?)
Also, get used to using paremeters in your queries:
cmd.CommandText = "Insert into StudentInfo(Rollno,SName,SFather,SAdress) Values (?,?,?,?)";
cmd.Parameters.Add(new OleDbParameter("#rollNo", rollNoValue)); //etc.
Related
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();
}
}
}
public partial class Form1 : Form
{
SqlConnection cn = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Dimmer\Documents\Visual Studio 2013\Projects\Manage components\Manage components\Database1.mdf;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
cmd.Connection = cn;
loadlist();
}
private void button1_Click(object sender, EventArgs e)
{
if (txtid.Text != "" & txtname.Text != "")
{
cn.Open();
cmd.CommandText = "insert into info (id,name) values ('"+txtid.Text+"'.'"+txtname.Text+"')";
cmd.ExecuteNonQuery();
cmd.Clone();
MessageBox.Show("Record instered!");
txtid.Text = "";
txtname.Text = "";
loadlist();
}
}
}
I am new to C# and I have been trying for some hours with a insert code to a service-based database. I have tested the connection to it and it works.
I got this error message:
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Incorrect syntax near 'xxxx'.
Where xxxx is what I insert into my 2nd textbox. The code stops at
cmd.ExcecuteNonQuery();
I have been searching for an answers for hours, I believe there is something wrong with the database.
Sorry if this code looks ugly, but I had some problems with spaces :P
You didn't tell us what are txtid.Text and txtname.Text exactly but..
You should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
cmd.CommandText = "insert into info (id,name) values (#id, #name)";
cmd.Parameters.AddWithValue("#id", txtid.Text);
cmd.Parameters.AddWithValue("#name", txtname.Text);
cmd.ExecuteNonQuery();
Looks like you're reusing a connection and you probably have not closed it last time.
You should always close a connection immediately as soon as you're finished with it. Use using statement like;
using(var cn = new SqlConnection(connectionString))
using(var cmd = new SqlCommand(query, cn))
{
if (txtid.Text != "" & txtname.Text != "")
{
cmd.CommandText = "insert into info (id,name) values (#id, #name)";
cmd.Parameters.AddWithValue("#id", txtid.Text);
cmd.Parameters.AddWithValue("#name", txtname.Text);
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
...
}
}
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().
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.
I'm Having some trouble deleting an entry on my database.
I can insert data, but i can't delete them.
I have a 2 variables database, and i want to manage those data.
but when i debug the program , the first button (btnAdicionar) works fine, but when i press the button "btnRemover", i get an erron on the line "cmd.ExecuteNonQuery();"
what am i doing wrong? thanks
here is the code:
private void btnAdicionar_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\\BancodeDados\\Nomes.mdb");
string sql = "INSERT INTO Nomes (Nome, Sobrenome) VALUES(?, ?)";
OleDbCommand cmd = new OleDbCommand(sql, conn);
conn.Open();
cmd.Parameters.AddWithValue("Nome", txtNome.Text);
cmd.Parameters.AddWithValue("Sobrenome", txtSobre.Text);
cmd.ExecuteNonQuery();
conn.Close();
this.nomesTableAdapter.Fill(this.nomesDataSet.Nomes);
}
private void btnRemover_Click(object sender, EventArgs e)
{
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\\BancodeDados\\Nomes.mdb");
string sql = "DELETE FROM Nomes (Nome, Sobrenome) WHERE (?, ?)";
OleDbCommand cmd = new OleDbCommand(sql, conn);
conn.Open();
cmd.Parameters.AddWithValue("Nome", txtNome.Text);
cmd.Parameters.AddWithValue("Sobrenome", txtSobre.Text);
cmd.ExecuteNonQuery();
conn.Close();
this.nomesTableAdapter.Fill(this.nomesDataSet.Nomes);
}
Your delete statement is not valid SQL, hence the error when you call ExecuteNonQuery
It should be something like this:
DELETE FROM Nomes WHERE Nome= ? and Sobrenome = ?