Hi I'm having a lot of truble doing a program in c#
i have to connect to SQLANYWHERE 11 and do an update to a table
could u tell me where I'm wrong?
program go well until i reach the:
int number = wCommand.ExecuteNonQuery(); line
the program doesnt crash but tables get not updated
string dns = "Dsn=dattest;Uid=******;Pwd=******;";
OdbcDataReader reader;
OdbcCommand wCommand;
ODBCClass dst1 = new ODBCClass(dns);
queryins = "UPDATE dba.Sala_export_dati_macchina_produzione SET stato='p'";
// +"WHERE id_prd_lav_ord_lav='"+ id_prd_lav_ord_lav + "'";
wCommand = dst1.GetCommand(queryins);
int number = wCommand.ExecuteNonQuery();
Console.WriteLine("executed "+ number);
this is the odbc class that i'm using
public class ODBCClass
{
OdbcConnection oConnection;
OdbcCommand oCommand;
public ODBCClass(string DataSourceName)
{
oConnection = new OdbcConnection(DataSourceName);
try
{
oConnection.Open();
System.Diagnostics.Trace.WriteLine("Connessione stabilita con il database " + DataSourceName);
}
catch (OdbcException caught)
{
System.Diagnostics.Trace.WriteLine(caught.Message);
}
}
public void CloseConnection()
{
oConnection.Close();
}
public OdbcCommand GetCommand(string Query)
{
oCommand = new OdbcCommand
{
Connection = oConnection,
CommandText = Query
};
return oCommand;
}
public void Dispose()
{
oConnection.Close();
}
}
EDIT
just in case i've tried to change connection string with this pattern:
#"Driver={SQL Anywhere 11};DatabaseName=my_db_name;EngineName=my_server_name;uid=username;pwd=password;LINKs=tcpip(host=host_ip_address)"
and always the system gave me no error on connection in both cases
Ok guys that was kinda strange.
Let me explain the whole thing. I was doing that program for a customer that asked a software which could link my mysql db and a sybase db of another company.
The problem was that the DBMS of that company when is opened on the server block all kind of external editing to the db with which is connected.
So select query worked regularly but update and insert were blocked by that client...
I've passed 4 day with a perfect working program but that company didn't told me this "little" thing.
So be aware of DBMS they are cruel.
Related
I am trying to update 2 columns in an Oracle database using C#. The columns I want to update are StartTime i.e. a timestamp and Name i.e. string. However when I run my code, the application freezes. I following is my code:
public int StartProduction(string serialNr, string empName)
{
string queryString = "UPDATE RO_EXEMPLAAR_PIM SET PLAKTAFEL_START=systimestamp, STARTED_BY=:startedBy WHERE SERIENR=:serialNr";
using (OracleConnection connection = new OracleConnection(connectionString))
{
using (OracleCommand command = new OracleCommand(queryString, connection))
{
try
{
OracleDataAdapter da = new OracleDataAdapter();
connection.Open();
command.Parameters.AddWithValue("serialNr", serialNr);
command.Parameters.AddWithValue("startedBy", empName);
da.InsertCommand = command;
int nrOfRecordsChanged = command.ExecuteNonQuery();
return nrOfRecordsChanged;
}
catch
{
return -1; //which means the try-block was not executed succesfully
}
finally
{
connection.Close();
}
}
}
}
I call it in a form as this:
if (dh.StartProduction(serialNr, empName) != -1)
{
MessageBox.Show("Production started successfully!");
}
else
{
MessageBox.Show("Production cannot be started!");
}
I looked up online and could not find what is wrong with my code. Thanks in advance!
Try a non locking read query like;
SELECT * FROM V$VERSION;
If that works (proving your connection string works).
Then you probably have a locking issue.
In general: (especially for devs)
Make sure you are not missing a "commit;" in your sql-developer or dbvisualizer or something like that. (or somebody on your dev team).
Running an update without a "commit;" in side these tools will lock a row.
If you can't find the culprit : a reboot of the server is in order.
I have the following INSERT method in a C# web project. If I run the project without MySQL connection poling everything works fine, but when I activate Pooling=True in the DB connection string this method stops working, the insert statements never complete.
I realized how to modify the code to make it work, but I would like to understand what is happening and I hope you could help.
When I comment line //myR.Close(); everything works fine.
using MySql.Data.MySqlClient;
//query example consulta="INSERT INTO users (id, name) VALUES (1, 'Rob');
public static MySqlConnection GetWriteConnection()
{
string connStr = MySqlConnectionStrings.WriteConnectionString;
MySqlConnection conn = new MySqlConnection(connStr);
return conn;
}
public static MySqlConnection GetReadConnection()
{
string connStr = MySqlConnectionStrings.ReadConnectionString;
MySqlConnection conn = new MySqlConnection(connStr);
return conn;
}
public static bool Insert(string consulta)
{
MySqlConnection conn = BdaHelper.GetWriteConnection();
conn.Open();
using (conn)
{
try
{
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
MySqlCommand micomando = new MySqlCommand(consulta, conn);
micomando.ExecuteNonQuery(); //still not working
return true;
}
catch (Exception ex)
{
return false;
}
}
}
My app has also multi-thread concurrency and two types of database connections, one specifically for only-read purposes and other different for write. When an insert statement fails I don't get any error simply the change doesn't commit in the database. Reading the article in the comments I don't think this applies to this issue but I would add an example of my main program:
MySqlConnection readConnection = BdaHelper.GetReadConnection();
using (readConnection)
{
var users = GetUsers(readConnection);
var credentials = GetCredentials(readConnection);
//Example is the query that fails don't giving any exception
Insert("INSERT INTO login_log (id_user, date) VALUES (1, now())");
}
May the problem be caused because there are two concurrent connections?
I shouldn't reuse read connection, even is a different connection than the write connection?
I'm writing a C# plugin for Autodesk Navisworks that will iterate through a bunch of 3D elements and write their properties (Category and Family of the element for now) into an Azure database.
I'm using Dapper as ORM. When I try to insert the data in the database Navisworks crashes giving an unhadled exception.
I tried the ssame procedure with plain sql and everything works fine so I'm quite sure it's Dapper's Execute function giving the exception.
This is my object:
internal class NavisTest
{
public string Category { get; set; }
public string Family { get; set; }
public NavisTest(string category, string family)
{
Category = category;
Family = family;
}
}
This is the sql command:
const string navisTestSql = "insert into NavisTest " +
"(Category, Family) " +
"values (#category, #family);";
And this is the main logic:
using (SqlConnection connection = new SqlConnection(
NavisDbSettings.ConnectToDB().ConnectionString))
{
// Open connection to db
connection.Open();
using (SqlTransaction transaction = connection.BeginTransaction())
{
NavisTest navisTest = new NavisTest(
"Wall",
"Concrete Wall 01");
connection.Execute(NavisDbSqlCommands.navisTestSql, navisTest, transaction: transaction);
// Commit database transaction
transaction.Commit();
}
}
So when this runs Navisworks just crashes, but if I do with a normal SqlCommand everything works fine.
(Also I basically copied the code to insert to the db from another application I have that works perfectly)
Also, if I try to surround the code in a try-catch clause, it still fails (it's an unhandled exception).
I really don't understand what I'm doing wrong.
Any ideas?
I'm a real noob in .NET and i'm trying to link a simple command line application (in C#) with a SQL server database. I'm now able to connect the program with the database but not to recover the data that are in it. Here is my code :
using System;
using System.Data;
using System.Data.SqlClient;
namespace ConsoleApplication1
{
class Program
{
static void Main()
{
string connectionString = GetConnectionString();
string queryString = "SELECT USER_ID FROM dbo.ISALLOCATEDTO;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = connection.CreateCommand();
command.CommandText = queryString;
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
int i = 0;
while (reader.Read())
{
i++;
Console.WriteLine("Field "+i);
Console.WriteLine("\t{0}",reader[0]);
}
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
//Console.WriteLine("Hello world");
string x = Console.ReadLine();
}
static private string GetConnectionString()
{
return "Data Source=FR401388\\SQLEXPRESS;Initial Catalog=Test;";
+ "Integrated Security=SSPI";
}
}
}
But when i'm running it and even if my table is not empty (I've seen it in the sql server studio), I cannot recover the data by using the read() method.
What I've done so far : try to change the name of the datatable with a fake one : the datatable is not found (so the link between sql server database and programm seems to be valid).
I'm using Windows Authentication in sql server, dunno if it's changing anything... (Once again : i'm very new to all of that).
Thanks !
Your code should work.
A possible cause is: You are looking at a different database.
This is quite common if you use Server Explorer inside VS with a connectionstring different from the one used in code.
This is my simple Code which stores parameters value in variables and use it on query
but it's give me ERROR message "INVALID Object name "DTA010.DFDR00" because I guess i'm not connected with the AS/400
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//string strQuery;
string order_no = Request.QueryString["order"];
if (order_no != null)
{
Response.Write("\n");
Response.Write("Order No is ");
Response.Write(order_no);
}
else
{
Response.Write("You Order number is not correct");
}
Response.Write("Your Order Status is");
Response.Write(niceMethod1());
Response.Write("\n");
}
public string niceMethod1()
{
string tDate = "";
string nOrder = (Request.QueryString["order"] ?? "0").ToString();
using (SqlConnection connection = new SqlConnection("Data Source=*****;User ID=web;Password=****;Initial Catalog=WEBSTATUS;Integrated Security=False;"))
{
string commandtext = "SELECT A.STAT01 FROM DTA010.DFDR00 AS A WHERE A.ORDE01 = #nOrder"; //#nOrder Is a parameter
SqlCommand command = new SqlCommand(commandtext, connection);
//command.Parameters.AddWithValue("#nPhone", nPhone); //Adds the ID we got before to the SQL command
command.Parameters.AddWithValue("#nOrder", nOrder);
connection.Open();
tDate = (string)command.ExecuteScalar();
} //Connection will automaticly get Closed becuase of "using";
return tDate;
}
}
The drivers needed to connect from a .NET application to a AS/400 are properly installed.
If the names of the schema (aka library) and table (aka file) are spelled correctly, try replacing the period with a slash /. This would be used for "system" naming syntax, rather than "standard" naming syntax.
You are definitely connected. I think the issue may be in the error you received. Make sure that the object exists that you are connecting to. WRKOBJ OBJ(BTGDTA010/DF01HDR00) will see if it exists. Check that everything is spelled right. It might be a typo.
Here is the simplest way I Found may be useful for someone..!!
First need to add Assembly IBM library and
using IBM.Data.DB2.iSeries;
then
iDB2Connection connDB2 = new iDB2Connection(
"DataSource=158.7.1.78;" +
"userid=*****;password=*****;DefaultCollection=MYTEST;");