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
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
hello i have a problem with getting exception of "ExecuteNonQuery requires an open and available Connection. The connection's current state is closed."
public void AddCustomer(Customer customer)
{
string connectionString = #"Data Source=LIRON-PC\SQLEXPRESS;Initial Catalog=C:\Program Files\Microsoft SQL Server\MSSQL12.SQLEXPRESS\MSSQL\DATA\MatokMmagnet.mdf;Integrated Security=True";
using (m_sqlConnection = new SqlConnection(connectionString))
{
m_cmd = new SqlCommand();
m_cmd.CommandType = CommandType.Text;
m_cmd.Connection = m_sqlConnection;
m_cmd.Parameters.AddWithValue("#id", customer.id);
m_cmd.Parameters.AddWithValue("#FirstName", customer.FirstName);
m_cmd.Parameters.AddWithValue("#LastName", customer.LastName);
m_cmd.Parameters.AddWithValue("#Password", customer.Password);
m_cmd.CommandText = "INSERT INTO Customers (id, FirstName, LastName, Password)VALUES (#id, #FirstName, #LastName, #Password)";
try
{
m_cmd.ExecuteNonQuery();
}
catch(Exception e)
{
Console.WriteLine( e.Message);
}
finally
{
m_sqlConnection.Close();
}
}
}
Like the error says you must open the connection before executing the query like this :
public void AddCustomer(Customer customer)
{
string connectionString = #"Data Source=LIRON-PC\SQLEXPRESS;Initial Catalog=C:\Program Files\Microsoft SQL Server\MSSQL12.SQLEXPRESS\MSSQL\DATA\MatokMmagnet.mdf;Integrated Security=True";
using (m_sqlConnection = new SqlConnection(connectionString))
{`
m_sqlConnection.open();
//....
}
}
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 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.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
Just startted with c#. not sure the express version supports connection to oracle or not.
if it does, could anyone let me know the steps to do it?
Thanks guys.
Use the ODP .NET ADO .NET Provider. You can see an example of how to use it here.
Copied from the example
using System;
using System.Data;
using Oracle.DataAccess.Client;
...
// Create the connection object
OracleConnection con = new OracleConnection();
// Specify the connect string
// NOTE: Modify User Id, Password, Data Source as per your database set up
con.ConnectionString = "User Id=userid;Password=password;Data Source=dbinstance;";
try
{
// Open the connection
con.Open();
Console.WriteLine("Connection to Oracle database established!");
Console.WriteLine(" ");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
string cmdQuery = "SELECT empno, ename FROM emptab";
// Create the OracleCommand object
OracleCommand cmd = new OracleCommand(cmdQuery);
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
try
{
// Execute command, create OracleDataReader object
OracleDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
// Output Employee Name and Number
Console.WriteLine("Employee Number: " +
reader.GetDecimal(0) +
" , " +
"Employee Name : " +
reader.GetString(1));
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
// Dispose OracleCommand object
cmd.Dispose();
// Close and Dispose OracleConnection object
con.Close();
con.Dispose();
}