How to insert into an identity column in MS SQL - c#

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();
}
}
}

Related

I want to insert data into a table

I'm building a C# Windows Forms database application. Data should be written in a text field and saved in a table using a button. My problem is that the data is not saved in the table.
I have built a list that should show the records of the table. When you click on the insert button, the text is displayed in the list, but it is not saved in the table.
My code:
private void insert_Click(object sender, EventArgs e)
{
string con_string = Properties.Settings.Default.DB1_ConnectionString;
SqlConnection con = new SqlConnection(con_string);
con.Open();
SqlCommand cmd = new SqlCommand("insert into tab_Musik values (#Titel,#Inerpret,#Genre)", con);
cmd.Parameters.AddWithValue("#Titel", int.Parse(txt_Titel.Text));
cmd.Parameters.AddWithValue("#Inerpret", txt_Interpret.Text);
cmd.Parameters.AddWithValue("#Genre", double.Parse(kmb_Genre.Text));
cmd.ExecuteNonQuery();
con.Close();
}
private void show[enter image description here][1]_Click(object sender, EventArgs e)
{
string con_string = Properties.Settings.Default.DB1_ConnectionString;
SqlConnection con = new SqlConnection(con_string);
con.Open();
SqlCommand cmd = new SqlCommand("select * from tab_Musik", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource=dt;
}
For the problem you described about clicking the insert button, the data cannot be saved to the table, you can try the following code:
private void btnAdd_Click(object sender, EventArgs e)
{
string con_string = "database connection string";
SqlConnection sqlConnection = new SqlConnection(con_string);
string myinsert = "insert into tab_Musik values (#Titel,#Inerpret)";
SqlCommand mycom = new SqlCommand(myinsert, sqlConnection);
mycom.Parameters.AddWithValue("#Titel", textBox1.Text);
mycom.Parameters.AddWithValue("#Inerpret", textBox2.Text);
sqlConnection.Open();
mycom.ExecuteNonQuery();
mycom.Clone();
mycom.Dispose();}
Show results:

How To delete from both database and datagridview

So i've been looking around the google for the anwser to this found so many diffrenet anwsers but i do not quite understand them and dont really see the way to implement them even thoug i have tryed alot so my issue is basicly that my delete button only deletes from the datagridview and not the database itself i do have the gridview bound to my knowledge but this is the very first form app i make so im a bit puzzeld to what i am doing
private void buttonDel_Click(object sender, EventArgs e)
{///////////////////////////////////////////////////////issue is here
foreach (DataGridViewRow item in this.dataGridView1.SelectedRows)
{
dataGridView1.Rows.RemoveAt(item.Index);
}
//string del = "DELETE FROM Data WHERE RowID = #RowID";
}
using (SqlConnection Connection = new SqlConnection(Connectionstring))
{
string query = "insert into data(Navn, NummerPlade, KMKørt, dato)";
query += " values (#Navn, #NummerPlade, #KMKørt, #dato)";
Connection.Open();
SqlCommand cmd = new SqlCommand(query, Connection);
cmd.Parameters.AddWithValue("#Navn", textBox1.Text);
cmd.Parameters.AddWithValue("#NummerPlade", textBox8.Text);
cmd.Parameters.AddWithValue("#KMKørt", textBox6.Text);
cmd.Parameters.AddWithValue("#dato", textBox7.Text);
cmd.ExecuteNonQuery();
Connection.Close();
button4_Click(sender, e);
}
private void button4_Click(object sender, EventArgs e)
{
/// Connect / Update
using (SqlConnection Connection = new SqlConnection(Connectionstring))
{
Connection.Open();
SqlDataAdapter sqlDa = new SqlDataAdapter("SELECT * FROM Data", Connection);
DataTable data = new DataTable();
sqlDa.Fill(data);
dataGridView1.DataSource = data;
}
buttonConn.Hide();
}

UpdateQuery not working with no errors

I can use these UpdateQuery on WinForms, now I convert it to ASP.NET Version and use this UpdateQuery again and not work. Others SELECT, INSERT, DELETE all works well, only update, also no error have given.
protected void updateBtn_Click(object sender, EventArgs e) {
DataTable dt = new DataTable();
string sql = "UPDATE patient SET ID=?ID, NameCH=?NameCH, NameEn=?NameEn, NRIC=?IC, Tel=?Tel, Email=?Email, Sex=?Sex, Occupation=?Occupation, Married=?Married, Address=?Address, Allergies=?Allergies, LTM=?LTM, MH=?MH, Other=?Other WHERE ( 'ID'=?ID )";
MySqlConnection con = new MySqlConnection(conStr);
MySqlCommand cmd = new MySqlCommand(sql, con);
cmd.Parameters.AddWithValue("?ID", ids.Text);
cmd.Parameters.AddWithValue("?NameCH", CHName.Text);
cmd.Parameters.AddWithValue("?NameEN", ENName.Text);
cmd.Parameters.AddWithValue("?IC", NRIC.Text);
cmd.Parameters.AddWithValue("?Tel", TEL.Text);
cmd.Parameters.AddWithValue("?Email", Email.Text);
cmd.Parameters.AddWithValue("?Sex", sex.Text);
cmd.Parameters.AddWithValue("?Occupation", occupation.Text);
if (married.Checked) {
cmd.Parameters.AddWithValue("?Married", "YES");
} else {
cmd.Parameters.AddWithValue("?Married", "NO");
}
cmd.Parameters.AddWithValue("?Address", address.Text);
cmd.Parameters.AddWithValue("?Allergies", Allergies.Text);
cmd.Parameters.AddWithValue("?LTM", ltm.Text);
cmd.Parameters.AddWithValue("?MH", medicalhis.Text);
cmd.Parameters.AddWithValue("?Other", record.Text);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Response.Redirect("~/Pages/Home.aspx/Update");
}

C# Listview , Data type Mismatch on insertion of record

I want to insert some data into Database Using C#
But I get below error
Error:Data type Mismatch when try to Execute
cmd1.ExecuteNonQuery();
private void btnFirst_Click(object sender, EventArgs e)
{
conString =Properties.Settings.Default.TransportationConnectionString;
con.ConnectionString = conString;
System.Data.OleDb.OleDbCommand cmd1 = new System.Data.OleDb.OleDbCommand();
cmd1.Connection = con;
cmd1.CommandText = "INSERT INTO [BillingGrd] ([InvoiceNo],[FromLocation],[ToLocation],[Material],[Trip],[MetricTon],[BillWeight],[Rate],[BillAmount],[GrandTotal]) Values (#InvoiceNo,#FromLocation,#ToLocation,#Material,#Trip,#MetricTon,#BillWeight,#Rate,#BillAmount,#GrandTotal)";
for(inc=0;inc<listView1.Items.Count;inc++)
{
cmd1.Parameters.AddWithValue("#InvoiceNo", txtBilNo.Text);
cmd1.Parameters.AddWithValue("#FromLocation", listView1.Items[inc].SubItems[0].Text);
cmd1.Parameters.AddWithValue("#ToLocation", listView1.Items[inc].SubItems[1].Text);
cmd1.Parameters.AddWithValue("#Material", listView1.Items[inc].SubItems[2].Text);
cmd1.Parameters.AddWithValue("#Trip", listView1.Items[inc].SubItems[3].Text);
cmd1.Parameters.AddWithValue("#MetricTon", listView1.Items[inc].SubItems[4].Text);
cmd1.Parameters.AddWithValue("#BillWeight", listView1.Items[inc].SubItems[5].Text);
cmd1.Parameters.AddWithValue("#Rate", listView1.Items[inc].SubItems[6].Text);
cmd1.Parameters.AddWithValue("#BillAmount", listView1.Items[inc].SubItems[7].Text);
cmd1.Parameters.AddWithValue("#GrandTotal", textBox1.Text);
}
con.Open();
cmd1.ExecuteNonQuery();//error here datatype mismatch
con.Close();
}
Try This might be work for you.....
if not Then let me know by comment
private void btnFirst_Click(object sender, EventArgs e)
{
conString =Properties.Settings.Default.TransportationConnectionString;
con.ConnectionString = conString;
System.Data.OleDb.OleDbCommand cmd1 = new System.Data.OleDb.OleDbCommand();
cmd1.Connection = con;
for(inc=0;inc<listView1.Items.Count;inc++)
{
cmd1.CommandText="";
con.Open();
cmd1.CommandText = "INSERT INTO [BillingGrd] ([InvoiceNo],[FromLocation],[ToLocation],[Material],[Trip],[MetricTon],[BillWeight],[Rate],[BillAmount],[GrandTotal]) Values ('"+txtBilNo.Text+"','"+listView1.Items[inc].SubItems[0].Text+"','"+listView1.Items[inc].SubItems[1].Text+"','"+listView1.Items[inc].SubItems[2].Text+"','"+listView1.Items[inc].SubItems[3].Text+"','"+listView1.Items[inc].SubItems[4].Text+"','"+listView1.Items[inc].SubItems[5].Text+"','"+listView1.Items[inc].SubItems[6].Text+"','"+listView1.Items[inc].SubItems[7].Text+'")";
cmd1.ExecuteNonQuery();//error here datatype mismatch
con.Close();
}
}

Can I call a sql command parameter from another class?

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.

Categories