I am getting above error during an insert query firebird,
Following is snippet of my code, i use odbc connection to perform and insert command
[ODBC Firebird Driver][Firebird]attempted update during read-only transaction
using (OdbcConnection cn = new OdbcConnection(string.Format("dsn={0};UID={1};PWD={2};", dsn, user, pwd)))
{
cn.Open();
foreach (var track in tracking)
{
string insertSQL = string.Format("INSERT INTO SHIPPINGIMPORT (TRACKINGNUM, SHIPCARTONID) VALUES ('{0}','{1}')",track.TrackingNum, track.CartonId);
using (OdbcCommand cmd = new OdbcCommand(insertSQL, cn))
{
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
}
}
Since I am using odbc connection, the fault was actually in the odbc connection configuration. You simply need to un-check the read (default write). Now it works like a charm. Hope this helps someone.
Related
I have a .NET web service application that executes parameterized MS SQL Server stored procedures using System.Data.SqlCommand. The application receives a name of the stored procedure and its parameters from user input.
Also the application deployed within Windows AD domain and it is able to obtain the name of a remote user with the help of SSPI authentication.
using (var con = new SqlConnection(connectionString)) {
using (var cmd = new SqlCommand(procedureName, con)) {
cmd.CommandType = CommandType.StoredProcedure;
foreach (var pair in pairs.AllKeys) {
cmd.Parameters.Add(new SqlParameter(pair, pairs[pair]));
}
con.Open();
using (var reader = cmd.ExecuteReader()) {
// processing results
}
}
}
Now I want to execute a stored procedure with an EXECUTE AS statement.
use [db]
go
execute as user = 'domain\user' --execute as RemoteUser
exec [db].[stored_procdure] #param1=value1
Can this be done? How can I add EXECUTE AS to the SqlCommand?
I would not like to resort to sql injection prone code and build the sql request from strings received from user.
Solved it some time ago with a colleague of mine.
To achieve the requested behavior the execute as statement should be run in a separate preceeding SqlCommand while in the same SqlConnection.
After the closing of the reader, still in the same SqlConnection, there's another separate SqlCommand needed - revert - to switch back the context.
I was having a similar issue where I was able to Execute as User but the Revert wasn't working. By following prot's answer I was able to fix it. So for anyone having a similar issue this is how the code looks
SqlCommand cmd = new SqlCommand("EXECUTE AS USER = 'domain\\user';");
OSSDBDataContext dc = new OSSDBDataContext();
cmd.Connection = dc.Connection as SqlConnection;
cmd.Connection.Open();
cmd.ExecuteNonQuery();
//Execute stored procedure code goes here
SqlCommand cmd2 = new SqlCommand("REVERT;");
cmd2.Connection = dc.Connection as SqlConnection;
cmd2.ExecuteNonQuery();
I'm trying to create backup and restore functionality to my Windows form application.
So, I've tried to do a database restore. My code is like this:
string cbdfilename = "c:\\Users\\Public\\Public Document";
SqlConnection.ClearAllPools();
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\BbCon.mdf;Integrated Security=True;Connect Timeout=30;");
string sql;
sql = "Use master;Alter Database BbCon Set Single_User With Rollback Immediate;Restore Database BbCon From Disk = #FILENAME With Replace;Alter Database BbCon Set Multi_User;";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#FILENAME", cbdfilename);
con.Open();
try
{
cmd.ExecuteNonQuery();
}
catch(Exception ex)
{
MessageBox.Show("Restore DB failed" + ex.ToString());
}
finally
{
con.Close();
con.Dispose();
}
But when I try to run this, I get an error:
Restore db failed System.Data.SqlClient.SqlException(0X80131904):userdoesnot have permission to alter database BbCon.mdf the database doesnot exist or or datbase is not in a state that allows access checks.
Can anyone help me please?
Are you trying to Backup or Restore? You mention Backup in the Title and the commmand is for Restore.
There're not many example cases for localDB yet.
Utilize my code as below. Hope this helps..
For Backup-
string master_ConnectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;Database=Master;Integrated Security=True;Connect Timeout=30;";
using (SqlConnection masterdbConn = new SqlConnection())
{
masterdbConn.ConnectionString = master_ConnectionString;
masterdbConn.Open();
using (SqlCommand multiuser_rollback_dbcomm = new SqlCommand())
{
multiuser_rollback_dbcomm.Connection = masterdbConn;
multiuser_rollback_dbcomm.CommandText= #"ALTER DATABASE yourdbname SET MULTI_USER WITH ROLLBACK IMMEDIATE";
multiuser_rollback_dbcomm.ExecuteNonQuery();
}
masterdbConn.Close();
}
SqlConnection.ClearAllPools();
using (SqlConnection backupConn = new SqlConnection())
{
backupConn.ConnectionString = yourConnectionString;
backupConn.Open();
using (SqlCommand backupcomm = new SqlCommand())
{
backupcomm.Connection = backupConn;
backupcomm.CommandText= #"BACKUP DATABASE yourdbname TO DISK='c:\yourdbname.bak'";
backupcomm.ExecuteNonQuery();
}
backupConn.Close();
}
For Restore-
string master_ConnectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;Database=Master;Integrated Security=True;Connect Timeout=30;";
using (SqlConnection restoreConn = new SqlConnection())
{
restoreConn.ConnectionString = master_ConnectionString;
restoreConn.Open();
using (SqlCommand restoredb_executioncomm = new SqlCommand())
{
restoredb_executioncomm.Connection = restoreConn;
restoredb_executioncomm.CommandText = #"RESTORE DATABASE yourdbname FROM DISK='c:\yourdbname.bak'";
restoredb_executioncomm.ExecuteNonQuery();
}
restoreConn.Close();
}
Update-
Oops, sorry, my code is for SQL localDB 2014 but it seems you're using 2012.
Kindly replace (LocalDB)\MSSQLLocalDB to (LocalDB)\v11.0
And kindly just try with above change.
And for your information, as per my experience, if I wrote |Data Directory| in my connectionString, I could only read (SQL SELECT command) the Database. In other word to say, the Insert and Update commands could be done but the database was not inserted or updated actually without any exception. I think setting as |Data Directory| would make the database as read-only and I've found some people were having difficulties to insert or update to database with |Data Directory| setting.
Hope your good days ! Thanks !
Is there anything wrong with this code? Please help me out.
protected void Button_Click(object sender, EventArgs e)
{
string cs = "Data Source=SFSIND0402;Initial Catalog=TestDB;Integrated Security=SSPI;Provider=Microsoft.ACE.OLEDB.12.0";
OleDbConnection conn = new OleDbConnection(cs);
conn.Open();
OleDbCommand insert = conn.CreateCommand();
insert.CommandText="insert into Employee(ID, Name, Sex, Salary) values('003','Vedpathi','M',25000)";
insert.Connection = conn;
insert.ExecuteNonQuery();
conn.Close();
}
I am getting the following error:
Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done
(on line 22:conn.Open();)
When connecting to an MS SQL database, use the MS SQL providers:
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
var cmd = new SqlCommand(commandText, connection);
cmd.ExecuteNonQuery();
}
In addition to the solution Luaan mentioned, you should store your connection string in the config file of the app and also encrypt it.
Even if you use SSL encryption when communicating with the DB, an ill-indended person can extract the string variables, if he / she runs the application on his / her machine.
I try to connect to a MySQL database on a server a friend of mine has created, but it still says it cannot connect to the server!
Here is my code:
String connectionString = "Persist Security Info=False;database=qwertyui;server=www.qwertyuiop.com;Uid=asdfghj;Pwd=qazwsxedc;Connect Timeout=30";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand cmd = new SqlCommand("INSERT INTO etc.... ");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue( etc.... );
connection.Open();
int r = cmd.ExecuteNonQuery();
}
It failes on the connection.Open() instruction throwing an exception -> cannot connect to the server.
Any ideas please?
SqlConnection is a SQL Server client.
You need to download a MySql client from NuGet.
First download the MySQL Connector.
Make sure you add a reference to the DLL (+ set copy local to true !)
Add using MySql.Data.MySqlClient; on top of your class.
As for the Connection String, do not add http or www in front of server. As it will try to connect to apache (port 80) instead to MySQL. The default port of MySQL is 3306.
string connectionString = "Persist Security Info=False;database=qwertyui;server=qwertyuiop.com;Uid=asdfghj;Pwd=qazwsxedc;port=3306";
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
string query = "INSERT INTO table VALUES (#parameter)";
connection.Open();
using (MySqlCommand cmd = new MySqlCommand(query, connection))
{
cmd.Parameters.AddWithValue("#parameter", parameter);
cmd.ExecuteNonQuery();
}
}
If this is not working. Make sure MySQL allows remote access, if this is not the case, you can keep trying forever without any result.
First thing that comes to mind is that you will have to use a MysqlConnection and command.
http://dev.mysql.com/doc/refman/5.0/es/connector-net-examples-mysqlconnection.html
Is it a local database?
And if with all of above does not work try to get grant to all privileges(GRANT Syntax)!
Basically it will go something like:
GRANT ALL PRIVILEGES ON DBname.* to 'username'#'IPadress' IDENTIFIED BY 'password';
My system write some data to a SQL Server DB (2008), extracts it later and processes it some more, before writing it to an Oracle (10g) DB.
I've wrapped my SQL Server interactions in a TransactionScope but when I try the same think with my Oracle interactions I get a `TranactionAbortedException - "The transaction has aborted".
Remove the TransactionScope, and everything works OK.
I could always revert back to manually managing my own transactions, but I'm hoping there is a simple solution.
Sample code:
private static void OracleTest()
{
using (TransactionScope ts = new TransactionScope())
{
using (OracleConnection conn = new OracleConnection(connString))
{
try
{
using (OracleCommand cmd = new OracleCommand())
{
cmd.CommandText = "MyPackage.MyFunction";
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Connection = conn;
OracleParameter param = cmd.Parameters.Add(new OracleParameter("field1_", "abc123"));
param = cmd.Parameters.Add(new OracleParameter("rs_", OracleType.Cursor));
param.Direction = System.Data.ParameterDirection.Output;
conn.Open();
using (OracleDataReader dr = cmd.ExecuteReader())
{
I haven't found anything to suggest that you can't use TransactionScopes with Oracle, but as you can see from my example, we're falling at the first hurdle (when we open the connection) so it's hard to see where I might be going wrong.
You may want to take a look at this; I haven't had much luck with TransactionScope in Oracle 10g either: http://forums.oracle.com/forums/thread.jspa?messageID=4127323