Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
I am developing a C# Windows application. I have used access database. When I selecting data from database I am getting data, but when inserting data it's not gets inserted and also it's not showing any error.
But when I run the same insert query in Access it gets inserted. Here is my code:
public void connCheck()
{
try
{
cn = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\Database\MyDatabase.mdb;Persist Security Info=True;Jet OLEDB:Database Password=2013");
if (cn.State == ConnectionState.Closed)
cn.Open();
}
catch (Exception exp)
{
MessageBox.Show(exp.ToString());
}
}
public bool ExecuteNonQuery()
{
try
{
connCheck();
string sqlQuery = "INSERT INTO tblResult(ExamSet,SetId,FullMarks,ObtainedMarks,MarksPercentage,ElapsedTime,LastQIndex,CreatedDate,Completed)
Values(1,27,'200.00',0,0,0,1,DATE(),'N')";
cmd.CommandType = CommandType.Text;
cmd.Connection = cn;
cmd.CommandText = sqlQuery;
cmd.ExecuteNonQuery();
return true;
}
catch(OleDbException ex)
{
ErrorMsg = ex.ToString();
return false;
}
finally
{
cn.Close();
cn.Dispose();
cmd.Dispose();
}
}
You did not defined your cmd..
add this line
OledbCommand cmd=new OledbCommand();
How about replacing your query code like this
string sqlQuery = "INSERT INTO tblResult([ExamSet],[SetId],[FullMarks],[ObtainedMarks],[MarksPercentage],[ElapsedTime],[LastQIndex],[CreatedDate],[Completed])
Values(1,27,'200.00',0,0,0,1,DATE(),'N')";
Update:
One of the issues could be Security warning that disables the content.
Try and see if this works (Go to your MDB):
Click on 'External Data' tab
There should be a Security Warning that states "Certain content in the database has been disabled"
Click the 'Options' button
Select 'Enable this content' and click the OK button
Try parameterised queries via cmd.Parameters.Add or AddRange. Example
var cmd = new SqlCommand("INSERT INTO tbl_name (a, b, c) VALUES (#a, #b, #c)");
cmd.Parameters.AddRange(new[] { new SqlParameter("#a", field1), new SqlParameter("#b", field2), new SqlParameter("#c", field2) });
(Posted on behalf of the OP).
Thanks everyone for your help, I got the solution. Actually there is no problem in my code. Problem is that I have created database file in a folder. But when I build the project it created a duplicate database with same folder an file name in bin folder.
So every time it gets inserted in that database. And I was checking in the database file which I have created. So I thought it's not working.
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 years ago.
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.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection cnn;
connetionString = "My_Connection";
cnn = new SqlConnection(connetionString);
try
{
cnn.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO person " +
"(name, lastname, phone) VALUES('#name', '#lastname', '#phone')");
cmd.CommandType = CommandType.Text;
cmd.Connection = cnn;
cmd.Parameters.AddWithValue("#name", txtName.Text);
cmd.Parameters.AddWithValue("#lastname", txtLastname.Text);
cmd.Parameters.AddWithValue("#phone", Convert.ToInt32(txtPhone.Text));
MessageBox.Show("Successful");
cnn.Close();
}
catch (SqlException ex)
{
MessageBox.Show("You failed!" + ex.Message);
}
}
There is a number of issues with this code. It appears that you're trying to reference a connection string from a configuration file. However, you can't just pass the name to the connection - you must actually retrieve it and assign it to your SqlConnection. Alternatively, you can hardcode a connection string, plenty of examples of those are available at connectionstrings.com.
It is usually not a good idea to put the connection string directly in your application however, as you need to reuse them throughout your application and it's best to have them declared in a central location.
private void button1_Click(object sender, EventArgs e)
{
// retrieve connection from configuration file
// requires a reference to System.Configuration assembly in your project
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["My_Connection"].ConnectionString;
//alternatively, hardcode connection string (bad idea!)
//string connectionString = "Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;";
using(SqlConnection connection = new SqlConnection(connectionString))
using(SqlCommand command = new SqlCommand("INSERT INTO person (name, lastname, phone) VALUES(#name, #lastname, #phone)", connection))
{
// you should avoid AddWithValue here, see http://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/
// thanks marc_s! http://stackoverflow.com/users/13302/marc-s
command.Parameters.AddWithValue("#name", txtName.Text);
command.Parameters.AddWithValue("#lastname", txtLastname.Text);
command.Parameters.AddWithValue("#phone", Convert.ToInt32(txtPhone.Text));
connection.Open();
command.ExecuteNonQuery();
}
MessageBox.Show("Successful");
}
The connection string is passed to the connection in its constructor, and the connection is passed to the command via its constructor.
Notice that there is no need to explicitly close the connection, the using statements take care of those for you. When the variable is out of scope, the connection will be closed, even if there is an exception.
An example of a connection string in your configuration file:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="My_Connection" providerName="System.Data.SqlClient" connectionString="Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;" />
</connectionStrings>
</configuration>
You have to write valid connetionString. If you ask what connection string is?
Here is answer
'In computing, a connection string is a string that specifies information about a data source and the means of connecting to it. It is passed in code to an underlying driver or provider in order to initiate the connection. Whilst commonly used for a database connection, the data source could also be a spreadsheet or text file.
The connection string may include attributes such as the name of the driver, server and database, as well as security information such as user name and password.'
Something like that
Server=myServerAddress;Database=myDataBase;User Id=myUsername; Password=myPassword;
They are a number of things to worry about when connecting to SQL Server on another machine.
Host/IP Address of the machine
Initial Catalog (database name)
Valid username/password
Very often SQL server may be running as a default intance which means you can simply specify the hostname/ip address but you may encounter a scenario where it is running as a named instance (Sql Express for instance). In this scenario you'll have to specify hostname\instance name
Your connection string is missing! Define it or get from your config. "My_Connection" doesn't contain server, database, user, password. Use something like:
var connectionString = "Data Source=ServerName; Initial Catalog=DataBaseName; User id=UserName; Password=Secret;";
using (SqlConnection connection = new SqlConnection("Data Source=ServerName; Initial Catalog=DatabaseName;User ID=UserName;Password=Password"))
{
using (SqlCommand command = new SqlCommand())
{
command.Connection = connection; // <== lacking
command.CommandType = CommandType.Text;
command.CommandText = "INSERT INTO person " +
"(name,lastname,phone) VALUES('#name', '#lastname', '#phone')";
cmd.Parameters.AddWithValue("#name", txtName.Text);
cmd.Parameters.AddWithValue("#lastname", txtLastname.Text);
cmd.Parameters.AddWithValue("#phone", Convert.ToInt32(txtPhone.Text));
try
{
connection.Open();
int recordsAffected = command.ExecuteNonQuery();
}
catch(SqlException)
{
// error here
}
finally
{
connection.Close();
}
}
}
Here is the working code.
Sincerely,
Thiyagu Rajendran
**Please mark the replies as answers if they help and unmark if they don't.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I have 2 forms in my program. I am using a SQL Server Compact 3.5 database file (.sdf) from C#
albums_tbl table has two columns: id, name
In form 1 when I use this code :
private void button1_Click(object sender, EventArgs e)
{
SqlCeCommand cm = new SqlCeCommand("INSERT INTO albums_tbl(album_name) VALUES (#album_name) ", cn);
cm.Parameters.AddWithValue("#album_name", textBox1.Text);
int affectedrows = cm.ExecuteNonQuery();
if (affectedrows > 0)
{
MessageBox.Show("insert shod !");
}
}
the program inserts well, but when I use the exact code in form 2 it errors this when I want to insert :
You don't open connection yet.
SqlCeConnection conn = null;
try
{
conn = new SqlCeConnection("Data Source = MyDatabase.sdf; Password ='<pwd>'");
conn.Open();
SqlCeCommand cmd = conn.CreateCommand();
cmd.CommandText = "INSERT INTO Customers ([Customer ID], [Company Name]) Values('NWIND', 'Northwind Traders')";
cmd.ExecuteNonQuery();
}
finally
{
conn.Close();
}
Refer: https://msdn.microsoft.com/en-us/library/system.data.sqlserverce.sqlceconnection(v=vs.100).aspx
Hope this helps.
You have not opened a connection , you just simply need to do as follow
private void button1_Click(object sender, EventArgs e)
{
SqlCeConnection con=new SqlCnConnection("Data Source = MyDatabase.sdf; Password ='<pwd>'");
SqlCeCommand cm = new SqlCeCommand("INSERT INTO albums_tbl(album_name) VALUES (#album_name) ", cn);
cm.Parameters.Add(new SqlCeParameter(#album_name, textBox1.Text));
con.Open();
cm.ExecuteNonQuery();
}
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I am trying to insert into database using this class, I am able to access this class in My Customer page, but getting error
Incorrect syntax near '#ZipCode'.
Meanwhile I don't have any stored procedure or trigger in my SQL Server database.
public class CustomerDLL
{
SqlConnection cn;
SqlCommand cmd;
SqlDataAdapter da;
DataSet ds;
public CustomerDLL()
{
cn = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
}
public void Insert_Customer(string name, string address, string city, string state, int ZipCode)
{
cmd = new SqlCommand("Insert into Customer values (#name, #address, #city, #state, #ZipCode", cn);
cmd.Parameters.AddWithValue("#name", name);
cmd.Parameters.AddWithValue("#address", address);
cmd.Parameters.AddWithValue("#city", city);
cmd.Parameters.AddWithValue("#state", state);
cmd.Parameters.AddWithValue("#ZipCode", Convert.ToInt32(ZipCode) ); // Line 34
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
}
I am accessing this class in Customer page using this method
protected void btnAdd_Click(object sender, EventArgs e)
{
// Create an instance of CustomerDll
CustomerDLL cusdll = new CustomerDLL();
//int zip = Convert.ToInt32(txtZip.Text);
cusdll.Insert_Customer
(
txtName.Text,
txtAddress.Text,
txtCity.Text,
txtState.Text,
Convert.ToInt32(txtZip.Text)
);
lblMsg.Text = "Rec is inserted successfully";
cusdll = null;
}
I keep getting error
Incorrect syntax near '#ZipCode' on line 34.
I think you missed closing parenthesis after #ZipCode.
I'm using Visual Studio 2010 to create a Win Form in c#. It has a handful of Comboboxes, and textboxes that the user can fill out and then submit to an Access DB. My issue comes in when I try to update existing entries. I load an existing entry, make my changes and click update. I do not get any system errors, my connection to the DB is successful, but no changes are actually made to the data. Am I completely missing something? Thanks in advance for any help or insight.
Here is the code for the update button:
private void updateButton_Click_1(object sender, EventArgs e)
{
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\servicereq1.mdb";
OleDbCommand cmd = new OleDbCommand("UPDATE servicereq SET DateLogged = #datelogged, LoggedBy = #loggedby, Function = #function, [Other Impacts] = #summary, Account = #earningsaccount, [From] = #from, [To] = #to, Description = #description, Fixer = #fixer, [Time Estimate] = #timeestimate, [Actual Start] = #actualstart, [Actual Finish] = #actualfinish, [Actual Time] = #actualtime, [Programs/Forms] = #programsforms, Comments = #comments, [Retest Date] = #requestdate, Tester = #tester, Status = #status, [Problem In Environment] = #problemfoundin, [Code In Environment] = #codein WHERE (ServiceRequestNumber = #servreq)");
cmd.Connection = conn;
conn.Open();
if (conn.State == ConnectionState.Open)
{
cmd.Parameters.AddWithValue("#servreq", serviceRequestNumberTextBox.Text);
cmd.Parameters.AddWithValue("#datelogged", dateLoggedTextBox.Text);
cmd.Parameters.AddWithValue("#loggedby", loggedByComboBox.Text);
cmd.Parameters.AddWithValue("#problemfoundin", problem_In_EnvironmentComboBox.Text);
cmd.Parameters.AddWithValue("#function", functionTextBox.Text);
cmd.Parameters.AddWithValue("#summary", other_ImpactsTextBox.Text);
cmd.Parameters.AddWithValue("#earningsaccount", accountTextBox.Text);
cmd.Parameters.AddWithValue("#from", fromTextBox.Text);
cmd.Parameters.AddWithValue("#to", toTextBox.Text);
cmd.Parameters.AddWithValue("#status", statusComboBox.Text);
cmd.Parameters.AddWithValue("#description", descriptionTextBox.Text);
cmd.Parameters.AddWithValue("#fixer", fixerComboBox.Text);
cmd.Parameters.AddWithValue("#codein", code_In_EnvironmentComboBox.Text);
cmd.Parameters.AddWithValue("#programsforms", programs_FormsTextBox.Text);
cmd.Parameters.AddWithValue("#timeestimate", time_EstimateTextBox.Text);
cmd.Parameters.AddWithValue("#actualstart", actual_StartTextBox.Text);
cmd.Parameters.AddWithValue("#actualfinish", actual_FinishTextBox.Text);
cmd.Parameters.AddWithValue("#actualtime", actual_TimeTextBox.Text);
cmd.Parameters.AddWithValue("#requestdate", retest_DateTextBox.Text);
cmd.Parameters.AddWithValue("#tester", testerComboBox.Text);
cmd.Parameters.AddWithValue("#comments", commentsTextBox.Text);
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("Form Updated Successfully");
conn.Close();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Message);
conn.Close();
}
}
else
{
MessageBox.Show("Connection Failed");
}
}
}
You shouldn't put your database parameters within quotes - they are evaluated as plain text instead of parameters if you do. There is no row where ServiceRequestNumber equals the literal string '#servreq', so nothing is updated.
Also, DataCommands don't pull in local variables as parameters - they must be explicitly added to the DataCommand object (cmd in this case). The reason you aren't getting any errors when you remove your parameter-adding code is because, as stated above, the query doesn't expect any parameters.
Also, the way parameters are being added in the code you removed is strange to say the least. This is much more normal, and significantly easier to read:
cmd.Paramaters.AddWithValue("#paramName", paramData);
//or
cmd.Parameters.Add(new OleDbParameter("#paramName", paramData));
After spending a little more time editing and moving code around, I stumbled on the fact that your parameters must be in the same order in the query as they are when you bind values to them. After making syntactical changes suggested by JoFlash Studios and putting my parameters in the correct order, I was able to make edits to existing data in my form.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I need to insert a record in Access 2000 database using C#. The code fails at the SqlConnection. Please help.
string connectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Trading.mdb";
string commandText = "INSERT INTO Order (OpenDate) VALUES (#OpenDate)";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(commandText, connection);
command.Parameters.AddWithValue("#OpenDate", DateTime.Now);
try
{
command.Connection.Open();
int response = command.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show("Error: {0}" + ex.Message);
}
}
Problem : you are working with MS-Access Database but using SqlServer objects.
Solution : you need to use OleDbConnection object instead of SqlConnection and OleDbCommand instead of SqlCommand
Try This:
string connectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Trading.mdb";
string commandText = "INSERT INTO Order (OpenDate) VALUES (?)";
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
OleDbCommand command = new OleDbCommand(commandText, connection);
command.Parameters.AddWithValue("#OpenDate", DateTime.Now);
try
{
command.Connection.Open();
int response = command.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show("Error: {0}" + ex.Message);
}
}
You need OleDbConnection not SqlConnection which is used for SQL Server.
See: Walkthrough: Editing an Access Database with ADO.NET
also: How to: Create Connections to Access Databases