I'm trying to update my database i.e. a MS Access file, I want to update my table by taking the values from the textboxes but I'm not able to write a proper query.
Can anyone please help me to write a proper update query?
string strconn4 = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|pay.accdb";
OleDbConnection sqlconn4 = new OleDbConnection(strconn4);
sqlconn4.Open();
OleDbCommand ocmd = new OleDbCommand("UPDATE fees SET fname=" + Convert.ToString(textBox2.Text) + ",lname=" + Convert.ToString(textBox3.Text) + ",amtpayd=" + Convert.ToString(textBox4.Text) + ",amtleft=" + Convert.ToString(textBox5.Text) + ",disc=" + Convert.ToString(textBox6.Text) + ",pdate=" + Convert.ToString(dateTimePicker3.Text) + ",rdate=" + Convert.ToString(dateTimePicker1.Text) + ",WHERE memid=" + Convert.ToString(textBox1.Text), sqlconn4);
Your code is prone to SQL injection which is a very serious security problem!
You should use parameterized queries instead.
Some links on how build such queries including references and samples:
http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbcommand.aspx
http://www.mikesdotnetting.com/Article/26/Parameter-Queries-in-ASP.NET-with-MS-Access
https://stackoverflow.com/a/4589424/847363
http://social.msdn.microsoft.com/Forums/en/accessdev/thread/33f3f6bc-03b2-4f64-84ca-cef65bbc0eee
Like this
string sql=string.Format("UPDATE Table1 SET column1='{0}',column2='{1}' where id={2}",tbx1.text,tbx2.text,tbx3.text);
SqlConnection conn = new SqlConnection();
conn.ConnectionString = strconn4;
SqlCommand cmd = new SqlCommand();
cmd.CommandText = sql;
cmd.Connection = conn;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
Related
I tried to adapt the solution from Understanding of nested SQL in C# Reply 4.
But it dont work. I cant find the mistake. Think it is something that the statement cant use a parameter as part of the table name.
string srcqry = #"USE [" + TableName+ "] " +
#"select TABLE_NAME from [INFORMATION_SCHEMA].[TABLES]";
using (SqlConnection srccon = new SqlConnection(cs))
using (SqlCommand srccmd = new SqlCommand(srcqry, srccon))
{
srccon.Open();
using (SqlDataReader src = srccmd.ExecuteReader())
{
string insqry = #"USE [" + TableName+ "] " + "ALTER SCHEMA "+SchemaNameNew+" TRANSFER [dbo].#tabelle";
// create new connection and command for insert:
using (SqlConnection inscon = new SqlConnection(cs))
using (SqlCommand inscmd = new SqlCommand(insqry, inscon))
{
inscmd.Parameters.Add("#tabelle", SqlDbType.NVarChar, 80);
inscon.Open();
while (src.Read())
{
inscmd.Parameters["#tabelle"].Value = src["TABLE_NAME"];
inscmd.ExecuteNonQuery();
}
}
}
}
I got the error that the statement is wrong in the #tabelle area.
Any idea why it wont work?
Thanks
I found a working solution.
while (src.Read())
{
var table= src["TABLE_NAME"];
var con = new System.Data.SqlClient.SqlConnection(cs);
con.Open();
var cmd = new System.Data.SqlClient.SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = #"USE [" + dbname+ "] " + "ALTER SCHEMA " + schemaname+ " TRANSFER [dbo]."+table;
cmd.ExecuteNonQuery();
con.Close();
}
I am trying to update an access table with the code noted below. however, the update does not execute. It doesn't give me any errors but it doesn't update the database. Any suggestions?
string Const = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\\Db\\test.accdb";
OleDbCommand Cmd;
OleDbConnection con22 = new OleDbConnection(Const );
con22.Open();
string sql = "UPDATE CostT SET tFormSent='" + Selection1.Text + "',TName='" + UserName.Text + "',FormDate='" + FormDate.Text + "',where ReqNum=" + ReqNum.Text;
cmd = new OleDbCommand(sql, con22);
cmd.ExecuteNonQuery();
con22.Close();
MessageBox.Show("Form has been Updated");
Try changing the query
to
string sql = "UPDATE CostT SET tFormSent = #selection1,TName = #UserName,FormDate = #FormDate where ReqNum = #ReqNum";
cmd = new OleDbCommand(sql, con22);
cmd.Parameters.Add("#selection1", Selection1.Text);
cmd.Parameters.Add("#UserName", UserName.Text);
cmd.Parameters.Add("#FromDate", FromDate.Text);
cmd.Parameters.Add("#ReqNum", ReqNum.Text);
cmd.ExecuteNonQuery();
con22.Close();
Your query has a syntax error: you have a comma before your WHERE clause that does not belong there.
But more important: Your code is open to SQL injection! Please don't insert user input directly into your query, but use parameterized queries instead!
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
protected void Button1_Click(object sender, EventArgs e)
{
int anInteger;
anInteger = Convert.ToInt32(txtmarks.Text);
anInteger = int.Parse(txtmarks.Text);
if (anInteger >= 60)
{
OleDbConnection con = new OleDbConnection();
con.ConnectionString =" Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\sakshi\\Documents\\m.accdb";
con.Open();
OleDbCommand cmd = new OleDbCommand();
OleDbDataAdapter adp = new OleDbDataAdapter();
OleDbDataReader rd;
cmd = new OleDbCommand("insert into student(fname,fmarks,fboard)values('" + txtname.Text + "','" + txtmarks.Text + "','" + ddlbrd.SelectedItem.ToString() + "'),con");
cmd.ExecuteNonQuery();
}
else
{
Response.Write("u are not elligible");
}
As mentioned in the comments on your question, you should look into parameterized queries, but right off it looks like you are not calling the OleDbCommand constructor properly.
You have:
cmd = new OleDbCommand("insert into student(fname,fmarks,fboard)values('" + txtname.Text + "','" + txtmarks.Text + "','" + ddlbrd.SelectedItem.ToString() + "'),con");
Which looks like you closed your string in the wrong place. Try the following instead:
cmd = new OleDbCommand("insert into student(fname,fmarks,fboard)values('" + txtname.Text + "','" + txtmarks.Text + "','" + ddlbrd.SelectedItem.ToString() + "')",con);
I would change my code to something like the following instead:
OleDbCommand cmd = new OleDbCommand(
"insert into student(fname,fmarks,fboard)values(#fname,#fmarks,#fboard);",
con
);
OleDbParameter parmName = cmd.CreateParameter();
parmName.ParameterName = "#fname";
parmName.OleDbType = OleDbType.VarChar;
parmName.Value = txtname.Text;
cmd.Parameters.Add(parmName);
OleDbParameter parmMarks = cmd.CreateParameter();
parmMarks.ParameterName = "#fmarks";
parmMarks.OleDbType = OleDbType.VarChar;
parmMarks.Value = txtmarks.Text;
cmd.Parameters.Add(parmMarks);
OleDbParameter parmBoard = cmd.CreateParameter();
parmBoard.ParameterName = "#fboard";
parmBoard.OleDbType = OleDbType.VarChar;
parmBoard.Value = ddlbrd.SelectedItem.ToString();
cmd.Parameters.Add(parmBoard);
Based on not initialised error, looks like you add con as a part of your sql command in your OleDbCommand constructor, not as a second parameter.
Change your
+ "'),con");
to
+ "')", con);
But I suggest a few things more;
You should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Delete your OleDbDataAdapter and OleDbDataReader definitions since you never use them.
Delete your anInteger = Convert.ToInt32(txtmarks.Text) line because it is identical with anInteger = int.Parse(txtmarks.Text) line.
Use using statement to dispose your connection and command automatically.
Open your connection just before when you execute your command. Move your con.Open() line just before your cmd.ExecuteNonQuery() line.
if(int.Parse(txtmarks.Text) > 60)
{
using(var con = new OleDbConneciton("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\sakshi\\Documents\\m.accdb"))
using(var cmd = con.CreateCommand())
{
cmd.CommandText = #"insert into student(fname,fmarks,fboard)
values(#fname, #fmarks, #fboard)";
// Add your parameters and their values with Add method and specifing their types
con.Open();
cmd.ExecuteNonQuery();
}
}
I'm having trouble with a SQL query:
using (SqlConnection conn = new SqlConnection("user id=user;" + "password=pass;" + "server=server;" + "database=db;"))
{
using (SqlCommand comm = new SqlCommand(#"SELECT COUNT(*) FROM [CompaniesDB].[dbo].[Companies] WHERE BolagsID = '" + BolagsID + "'"))
{
conn.Open();
comm.Connection = conn;
MessageBox.Show("TEST: {0}", Convert.ToString((int)comm.ExecuteScalar()));
}
}
I'm expecting to get an int in the message box conveying the number of rows that BolagsID occurs in. But I get 0 every time. I've tried the query in SQL Server Management Studio and it works fine there. What am I doing wrong/missing?
EDIT:
This works, but now I don't know how to parameterize the values:
string query = #"SELECT COUNT(*) FROM [CompaniesDB].[dbo].[Companies] WHERE BolagsID = " + BolagsID;
ADODB.Connection conn2 = new ADODB.Connection();
ADODB.Recordset rs = new ADODB.Recordset();
string strConn = "Provider=...;Data Source=...;Database=...;User Id=...;Password=...";
conn2.Open(strConn);
rs.CursorType = ADODB.CursorTypeEnum.adOpenStatic;
rs.Open(query, conn2);
if (rs.Fields[0].Value > 0)
...stuff...
Like others are saying, parameters are a good idea. Here's something to get you started:
string query = #"SELECT Count(*) FROM [CompaniesDB].[dbo].[Companies] WHERE BolagsID = #BolagsID";
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.Add("#BolagsID", SqlDbType.NVarChar).Value = BolagsID;
conn.Open();
MessageBox.Show("TEST: {0}", Convert.ToString((int)cmd.ExecuteScalar()));
conn.Close();
}
Basically a 0 is returned if there is an error in your query, so even though SSMS is smart enough to resolve it, the sql command isn't.
A quick way to make sure that everything else is working okay is to change the query to just "SELECT Count(*) FROM [CompaniesDB].[dbo].[Companies]". If that doesn't work then the issue could lie with your database connection (permissions?) or something else.
Try assigning SELECT COUNT(*) FROM [CompaniesDB].[dbo].[Companies] WHERE BolagsID = '" + BolagsID + "'" to a string str as follows
string str =#"SELECT COUNT(*) FROM [CompaniesDB].[dbo].[Companies] WHERE BolagsID = '" + BolagsID + "'";
using (SqlConnection conn = new SqlConnection("user id=user;" + "password=pass;" + "server=server;" + "database=db;"))
{
using (SqlCommand comm = new SqlCommand(str))
{
conn.Open();
comm.Connection = conn;
MessageBox.Show("TEST: {0}", Convert.ToString((int)comm.ExecuteScalar()));
}
}
Then do a watch/quickwatch on str's value to get the exact query that is getting run and then run the same query in Sql Managment studio. If you get 0 in Sql Management Studio as well, then the problem is that the data is just not there.
I tried a lot of stuff before trying out a whole different approach. This gives me the result I want:
string query = #"SELECT COUNT(*) FROM [CompaniesDB].[dbo].[Companies] WHERE BolagsID = " + BolagsID;
ADODB.Connection conn2 = new ADODB.Connection();
ADODB.Recordset rs = new ADODB.Recordset();
string strConn = "Provider=...;Data Source=...;Database=...;User Id=...;Password=...";
conn2.Open(strConn);
rs.CursorType = ADODB.CursorTypeEnum.adOpenStatic;
rs.Open(query, conn2);
if (rs.Fields[0].Value > 0)
...stuff...
Note that both connection and record set are closed outside of this code snippet.
i have database in access with auto increase field (ID).
i insert record like this (in C#)
SQL = "insert into TermNumTbl (DeviceID,IP) values ('" + DeviceID + "','" + DeviceIP + "') ";
OleDbCommand Cmd = new OleDbCommand(SQL, Conn);
Cmd.ExecuteNonQuery();
Cmd.Dispose();
Conn.Close();
how to get the last inserting number ?
i dont want to run new query i know that in sql there is something like SELECT ##IDENTITY
but i dont know how to use it
thanks in advance
More about this : Getting the identity of the most recently added record
The Jet 4.0 provider supports ##Identity
string query = "Insert Into Categories (CategoryName) Values (?)";
string query2 = "Select ##Identity";
int ID;
string connect = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|Northwind.mdb";
using (OleDbConnection conn = new OleDbConnection(connect))
{
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
cmd.Parameters.AddWithValue("", Category.Text);
conn.Open();
cmd.ExecuteNonQuery();
cmd.CommandText = query2;
ID = (int)cmd.ExecuteScalar();
}
}
I guess you could even write an extension method for OleDbConnection...
public static int GetLatestAutonumber(
this OleDbConnection connection)
{
using (OleDbCommand command = new OleDbCommand("SELECT ##IDENTITY;", connection))
{
return (int)command.ExecuteScalar();
}
}
I like more indicate the type of command
is very similar to the good solution provided by Pranay Rana
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = sql_Insert;
cmd.ExecuteNonQuery();
cmd.CommandText = sql_obtainID;
resultado = (int)comando.ExecuteScalar();
}
query = "Insert Into jobs (jobname,daterecieved,custid) Values ('" & ProjectNAme & "','" & FormatDateTime(Now, DateFormat.ShortDate) & "'," & Me.CustomerID.EditValue & ");"'Select Scope_Identity()"
' Using cn As New SqlConnection(connect)
Using cmd As New OleDb.OleDbCommand(query, cnPTA)
cmd.Parameters.AddWithValue("#CategoryName", OleDb.OleDbType.Integer)
If cnPTA.State = ConnectionState.Closed Then cnPTA.Open()
ID = cmd.ExecuteNonQuery
End Using
Using #Lee.J.Baxter 's method (Which was great as the others id not work for me!) I escaped the Extension Method and just added it inline within the form itself:
OleDbConnection con = new OleDbConnection(string.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='{0}'", DBPath));
OleDbCommand cmd = con.CreateCommand();
con.Open();
cmd.CommandText = string.Format("INSERT INTO Tasks (TaskName, Task, CreatedBy, CreatedByEmail, CreatedDate, EmailTo, EmailCC) VALUES('{0}','{1}','{2}','{3}','{4}','{5}','{6}')", subject, ConvertHtmlToRtf(htmlBody), fromName, fromEmail, sentOn, emailTo, emailCC);
cmd.Connection = con;
cmd.ExecuteScalar();
using (OleDbCommand command = new OleDbCommand("SELECT ##IDENTITY;", con))
{
ReturnIDCast =(int)command.ExecuteScalar();
}
NOTE: In most cases you should use Parameters instead of the string.Format() method I used here. I just did so this time as it was quicker and my insertion values are not coming from a user's input so it should be safe.
Simple,
What we do in excel for copy text in above cell?
Yes, just ctrl+" combination,
and yes, it's work in MS ACCESS also.
You can use above key stroke combination for copy above records field text, just make sure if you have duplicate verification applied or edit field data before move next field.
If you aspects some more validation or any extraordinary then keep searching stack overflow.