Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm trying to do a simple C# windows application as a beginner. But I get a System.Data.SqlClient.SqlException. When I try to connect to database it says connection is OK. But it doesn't allow me to create any tables using visual studio. I can't figure out why it doesn't show options to add new table.
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.Windows.Forms;
using System.Data.SqlClient;
namespace best
{
public partial class Form1 : Form
{
SqlConnection con=new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Janith Kularathne\Documents\testing.mdf;
Integrated Security=True;Connect Timeout=30");
public Form1()
{
InitializeComponent();
}
private void insertB_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Insert into details values('"+ idBox.Text +"', '"+ nameBox.Text + "')";
cmd.ExecuteNonQuery();
con.Close();
idBox.Text = "";
nameBox.Text="";
DisplayDetails();
MessageBox.Show("Insertion succesfull");
}
private void deleteB_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Delete from details where id= '" + idBox.Text + "')";
cmd.ExecuteNonQuery();
con.Close();
idBox.Text = "";
nameBox.Text = "";
DisplayDetails();
MessageBox.Show("delete succesfull");
}
private void updateB_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update details set id, name,category where id= '" + idBox.Text + "')";
cmd.ExecuteNonQuery();
con.Close();
idBox.Text = "";
nameBox.Text = "";
DisplayDetails();
MessageBox.Show("Update succesfull");
}
private void searchB_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "selet *from details where id= '" + idBox.Text + "')";
cmd.ExecuteNonQuery();
con.Close();
DisplayDetails();
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
DisplayDetails();
}
public void DisplayDetails()
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from details";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
}
Your code currently contains a variety of different issues, which I'll elaborate a bit on and should resolve some of your current problems :
Unnecessary closing parentheses
Typos and Misspellings
Incorrect Syntax
Using Parameterization
In addition to these, I'd highly recommend reading through some tutorials on using the different methods like ExecuteNonQuery(), ExecuteReader() and ExecuteNonScalar() to determine how to actual retrieve values from your queries once you execute them.
Unnecessary Closing Parentheses
You currently have a trailing closing parentheses within each of your queries which is likely causing a syntax error within your SELECT, UPDATE, and DELETE queries :
// Notice the unnecessary trailing ')', which should only be useful within your INSERT call
cmd.CommandText = "..." + idBox.Text + "')";
Typos and Misspellings
An additional typo is present within your search query as well as the word "SELECT" is misspelled:
// "selet" should be "Select"
cmd.CommandText = "selet *from details where id= '" + idBox.Text + "')";
Incorrect Syntax
Your current UPDATE query doesn't actually appear to be doing anything. You are using the SET keyword, but aren't actually setting the values to anything :
// UPDATE queries should be in the form UPDATE {table} SET {Column} = {Value} WHERE ...
cmd.CommandText = "update details set id, name,category where id= '" + idBox.Text + "')";
Parameterization, Not Concatenation
Additionally, you should really consider using parameterization when building your queries. It can help avoid nastiness like SQL Injection and prevent syntax errors as well.
You can see an example of what this might look like for one of your methods below :
private void searchB_Click(object sender, EventArgs e)
{
con.Open();
var query = "SELECT * FROM details WHERE ID = #id";
using(var cmd = new SqlCommand(query, connection))
{
cmd.Parameters.AddWithValue("#id",idBox.Text);
using(var reader = cmd.ExecuteReader())
{
// Access your results here and do something with them
}
}
}
Related
I am trying to edit an Access DB_. For some reason I cannot insert anything. I believe my code is correct. The connection string is correct (though for security purposes I put a fake one for this post). At the end, I do not get the MessageBox like I am supposed to at the end of the function. Nothing was added to the Access DB either.
Any reason why this might be?
namespace TestBuild
{
public partial class Form1 : Form
{
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users...\Documents\TestDB.accdb");
public Form1()
{
InitializeComponent();
}
private void Button1_Click(object sender, EventArgs e)
{
con.Open();
OleDbCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into table1 values('"+textBox1.Text+"','"+textBox2.Text+"')";
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("record inserted successfully");
}
}
}
Suggestion - please consider refactoring your code as follows, and step through it, a line at a time, in the MSVS debugger:
string connString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users...\Documents\TestDB.accdb";
private void Button1_Click(object sender, EventArgs e)
{
string sql = "insert into table1 values('" + textBox1.Text + "','" + textBox2.Text + "')";
OleDbCommand cmd= new OleDbCommand(sql);
using (OleDbConnection con = new OleDbConnection(connString)) {
cmd.Connection = conn;
try
{
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("record inserted successfully");
}
catch (Exception ex)
{
MessageBox.Show("ERROR" + ex.Message);
}
}
}
PS:
If you wanted to use prepared statements, you'd change your code to something like this:
string sql = "insert into table1 values(#param1, #param2)";
...
cmd.Parameters.AddWithValue("#param1", textBox1.Text);
cmd.Parameters.AddWithValue("#param1", textBox2.Text);
con.Open();
cmd.Prepare();
cmd.ExecuteNonQuery();
You can read more about techniques and guidelines for mitigating SQL injection here:
https://www.owasp.org/index.php/SQL_Injection_Prevention_Cheat_Sheet
Here is another good article:
Best Practices for Using ADO.NET (MSDN)
I know this title seems to be repeated a lot but I tried to search and didn't find the answer.
Code:
using System;
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 _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e) {}
protected void gv_master_SelectedIndexChanged(object sender, EventArgs e)
{
// Get the currently selected row using the SelectedRow property.
GridViewRow row = gv_master.SelectedRow;
// Display the first name from the selected row.
// In this example, the third column (index 2) contains
// the first name.
lbl_reqNoV.Text = row.Cells[1].Text;
lbl_reqNoV.Visible = true;
lbl_reqNo.Visible = true;
SqlConnection sqlConnection1 = new SqlConnection("Data Source=saitest01;Initial Catalog=SAI_website;Persist Security Info=True;User ID=sa;Password=sai#987");
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Select * from purchase Where ReqNo = '" + lbl_reqNoV.Text + "', sqlConnection1";
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
SqlDataReader DR1;
DR1 = cmd.ExecuteReader();
DR1.Read();
// Data is accessible through the DataDR1 object here
gv_full.DataSource = DR1;
gv_full.DataBind();
}
}
the problem is you where adding the name of Connection in the query text which is ofcource not recognized by sqlserver the correct format was
var cmd = new SqlCommand("Select * from purchase Where ReqNo = #reqno",sqlConnection1)
or you can do this
cmd.CommandText = "Select * from purchase Where ReqNo = #reqno";
cmd.Parameters.AddWithValue("reqno",lbl_reqNoV.Text);
cmd.CommandType = CommandType.Text;
cmd.Connection = sqlConnection1;
you should always use parameters in query to avoid Sql Injection
just change following
cmd.CommandText = "Select * from purchase Where ReqNo = '" + lbl_reqNoV.Text + "', sqlConnection1";
with,
cmd.CommandText = "Select * from purchase Where ReqNo = '" + lbl_reqNoV.Text + "' ";
Above will make your code working. But you should modify you code to handle SQL Injection. As answered by #Usman
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public partial class Editprofile : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["ProfileCS"].ConnectionString;
string sql = "select userid from Profile";
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
DataTable dt = new DataTable();
cmd.CommandText = sql;
cmd.Connection = con;
con.Open();
dr = cmd.ExecuteReader();
dt.Load(dr);
ddl_userid.DataSource = dt;
ddl_userid.DataTextField = "userid";
ddl_userid.DataValueField = "userid";
ddl_userid.DataBind();
}
}
protected void ddl_userid_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["ProfileCS"].ConnectionString;
string sql = "Select studname,gender,email,birthdate,contact from profile where userid='" + ddl_userid.SelectedValue + "'";
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
DataTable dt = new DataTable();
cmd.CommandText = sql;
cmd.Connection = con;
con.Open();
dr = cmd.ExecuteReader();
dt.Load(dr);
tb_studname.Text = dt.Rows[0]["studname"].ToString();
tb_gender.Text = dt.Rows[0]["gender"].ToString();
tb_email.Text = dt.Rows[0]["email"].ToString();
tb_age.Text = dt.Rows[0]["birthdate"].ToString();
tb_contact.Text = dt.Rows[0]["contact"].ToString();
Session["dt"] = dt;
}
protected void bn_reset_Click(object sender, EventArgs e)
{
DataTable dt = (DataTable)Session["dt"];
tb_studname.Text = dt.Rows[0]["studname"].ToString();
tb_gender.Text = dt.Rows[0]["gender"].ToString();
tb_email.Text = dt.Rows[0]["email"].ToString();
tb_age.Text = dt.Rows[0]["birthdate"].ToString();
tb_contact.Text = dt.Rows[0]["contact"].ToString();
}
protected void bn_update_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["ProfileCS"].ConnectionString;
String name = tb_studname.Text;
String gender = tb_gender.Text;
String email = tb_email.Text;
String age = tb_age.Text;
String contact = tb_contact.Text;
string sql="Update Profile Set studName='"+name+"',gender='"+gender+"',email='"+email+"',birthdate='"+age+"',contact='"+contact;
sql=sql +"where userid='"+ddl_userid+"'";
SqlCommand cmd =new SqlCommand();
cmd.CommandText=sql;
cmd.Connection=con;
try
{
con.Open();
cmd.ExecuteNonQuery();
lbl_msg.Text="Record Updated!";
}
catch(Exception ex)
{
lbl_msg.Text="Problem encountered:"+ex.Message;
}
finally
{
con.Close();
con.Dispose();
cmd.Dispose();
}
}
}
HI guys when i load the page the reset button works as intended but when i try the update info button error message occurs as such
Problem encountered:Incorrect syntax near 'System'. Unclosed quotation mark after the character string ''
The error is in missing close quote in the update statement
string sql="Update Profile Set studName='"+name+"',gender='"+gender+"',email='"+
email+"',birthdate='"+age+"',contact='"+contact +"'";
Said that, you should remove all this string concatenation and use a parameterized query
There are too many point to fix, I just show a proposed fix for the Update
string sql="Update Profile Set studName=#name,gender=#gender,email=#email," +
"birthdate=#age,contact=#contact where userid=#uid";
SqlCommand cmd =new SqlCommand();
cmd.CommandText = sql;
cmd.Parameters.AddWithValue("#name",name);
cmd.Parameters.AddWithValue("#gender",gender);
cmd.Parameters.AddWithValue("#email",email);
cmd.Parameters.AddWithValue("#age",age);
cmd.Parameters.AddWithValue("#contact",contact);
cmd.Parameters.AddWithValue("#uid",ddl_userid);
cmd.ExecuteNonQuery();
In this way your command string is more readable and you avoid subtle quoting errors.
Also the work to quote your parameters is passed to the framework code and there is no possibility of SQL Injections.
I think the problem in this line;
string sql="Update Profile Set studName='"+name+"',gender='"+gender+"',email='"+email+"',birthdate='"+age+"',
contact='"+contact;
^^ here missing '"
sql=sql +"where userid='"+ddl_userid+"'";
But please don't use this way. Use parameterized queries instead. This kind of string concatenations are open for SQL Injection attacks.
Also using parameterized queries increases readability.
For example;
string sql = #"Update Profile Set studName=#studName,gender=#gender,email=#email, birthdate=#birthdate, contact=#contact
where userid=#userid";
SqlCommand cmd =new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#studName", studName);
cmd.Parameters.AddWithValue("#gender", gender);
cmd.Parameters.AddWithValue("#email", email);
cmd.Parameters.AddWithValue("#birthdate", birthdate);
cmd.Parameters.AddWithValue("#contact", contact);
cmd.Parameters.AddWithValue("#userid", userid);
cmd.ExecuteNonQuery();
Issue with Following line:
string sql="Update Profile Set studName='"+name+"',gender='"+gender+"',email='"+email+"',birthdate='"+age+"',contact='"+contact;
You need to complete the string as follow : see I have edited end of the statement.
string sql="Update Profile Set studName='"+name+"',gender='"+gender+"',email='"+email+"',birthdate='"+age+"',contact='"+contact +"' ";
Note : I am suggesting to you that you should use parameterized query instead of making direct string.
Change:
string sql="Update Profile Set studName='"+name+"',gender='"+gender+"',email='"+email+"',birthdate='"+age+"',contact='"+contact;
To:
string sql="Update Profile Set studName='"+name+"',gender='"+gender+"',email='"+email+"',birthdate='"+age+"',contact='"+contact + "' ";
Missing the single quote after contact. Then you need a space so that the next line that adds Where clause works.
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 have a Form where I am inserting a record into the database. There are two tables, table_1 is called members, and table_2 is called Amount.
I am using two SQL INSERT statements to send records to database , because that’s the way I have figured out -- there might be other ways, which I don’t know.
When I insert the record I get a message that it is inserted successfully, but when I check the database the inserted record replaces the one present , so I have last record in the DB repeated several times. Please assist.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace CemiyetAidatSistem
{
public partial class AddMember : Form
{
public AddMember()
{
InitializeComponent();
}
SqlConnection con = new SqlConnection("Data Source=My-PC\\SQLSERVER;Initial Catalog=FredericiaDernek;Integrated Security=True");
private void btnInsert_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand();
string Sql = "INSERT INTO Uyeleri ( dID, FullName, Address, Mobile, Email, Comments ) VALUES ('" + txtdID.Text + "', '" + txtAdiSoyadi.Text + "','" + txtAddress.Text + "','" + txtMobile.Text + "','" + txtEmail.Text + "','" + txtComments.Text + "')";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Sql = "INSERT INTO Aidat (dID Year, Amount ) VALUES ('"+ txtdID.Text +"','" + txtYear.Text + "','" + txtAmount.Text + "')";
cmd.CommandText = Sql;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
for (int i = 0; i < this.Controls.Count; i++)
{
if (this.Controls[i] is TextBox)
{
this.Controls[i].Text = "";
}
}
MessageBox.Show("Data Added Scuessfully");
}
}
}
I have rewritten your code to correct errors and bad practices
string connString = "Data Source=My-PC\\SQLSERVER;Initial Catalog=FredericiaDernek;Integrated Security=True";
private void btnInsert_Click(object sender, EventArgs e)
{
using(SqlConnection con = new SqlConnection(connString))
{
con.Open();
string Sql = "INSERT INTO Uyeleri (dID, FullName, Address, Mobile, Email, Comments ) " +
"VALUES (#id, #name, #address, #mobile, #email, #comments");
using(SqlCommand cmd = new SqlCommand(Sql, con))
{
cmd.Parameters.AddWithValue("#id", txtdID.Text);
cmd.Parameters.AddWithValue("#name", txtAdiSoyadi.Text);
cmd.Parameters.AddWithValue("#address", txtAddress.Text);
cmd.Parameters.AddWithValue("#mobile", txtMobile.Text);
cmd.Parameters.AddWithValue("#email", txtEmail.Text);
cmd.Parameters.AddWithValue("#comments", txtComments.Text);
cmd.ExecuteNonQuery();
Sql = "INSERT INTO Aidat (dID, [Year], Amount ) VALUES " +
"(#id, #year, #amount)";
cmd.Parameters.Clear();
cmd.CommandText = Sql; // <- missing this in the previous version.....
cmd.Parameters.AddWithValue("#id", txtdID.Text);
cmd.Parameters.AddWithValue("#name", txtYear.Text);
cmd.Parameters.AddWithValue("#amount", txtAmount.Text);
cmd.ExecuteNonQuery();
}
}
What I have changed:
The second insert statement is wrong. Missing a comma between first
and second column
Removed the creation of the SqlConnection at the global level
Added appropriate using statement to dispose the SqlConnection and
SqlCommand also in case of exceptions
Used parameters for the two insert statements
Added square brackets around Year field (Year is a reserved keyword
in T-SQL)
Creating a SqlConnection at the global level is bad, because you grab system resources and you don't dispose them for the lifetime of your application. And the situation could be out of control in case of exceptions not correctly handled.
Now I have some doubt about your tables. The fields dID (both tables) and Amount are of text type (varchar,nvarchar)?. If they are of numeric type it is necessary to add a conversion before adding the values to the Parameters collection
I would also suggest changing your for loop to clear the controls replace this
for (int i = 0; i < this.Controls.Count; i++)
{
if (this.Controls[i] is TextBox)
{
this.Controls[i].Text = "";
}
}
with the following code using linq.
this.Controls.OfType<TextBox>().ToList().ForEach(textBox => textBox.Clear());
keep in mind that 'this' will refer to the name of your Form
so it would be
(YourWinFormsName).Controls.OfType<TextBox>().ToList().ForEach(textBox => textBox.Clear());