Using MySQL stored procedure in Asp.Net C# - c#

I can not find what is the error in this code. According to me it's good and hope to execute properly but I am getting an error:
ERROR [42000] [MySQL][ODBC 3.51 Driver][mysqld-5.7.11]
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ViewBatchByID' at line 1
My code Is
string Message = null;
OdbcCommand Cmd = new OdbcCommand();
Cmd.Connection = Connection.con;
Cmd.CommandText = "ViewBatchByID";
Cmd.CommandType = CommandType.StoredProcedure;
Cmd.Parameters.AddWithValue("#p0", 1);
try
{
Cmd.ExecuteNonQuery();
}
catch(Exception ex)
{
Message = ex.Message.ToString();
}
HERE ViewBatchByID is my stored procedure and it's working fine from server.

Check the connection settings for the server. Is the Database set?
Driver={SQL Server};Server=(local);Trusted_Connection=Yes;Database=AdventureWorks;

Related

Unable to connect to any of the specified MySQL hosts

I know that it is an easy problem but I can't find the error. I want to save data in my database. I create a database named "Examen" with Microsoft SQL Server 2008 then in my app in visual studio I make the connection string like this :
string connectionstring = #"Data Source=.\sqlexpress;Initial Catalog=Examen;Integrated Security=True";
Then I use this code to insert data into a "Test" table:
MySqlConnection connection = new MySqlConnection(connectionstring);
MySqlCommand cmd;
connection.Open();
try
{
cmd = connection.CreateCommand();
cmd.CommandText = "Insert into Examen.Test (nom,prenom) values (" + txbnom.Text + "," + txbprenom.Text + ") ";
cmd.ExecuteNonQuery();
MessageBox.Show("ok");
}
catch (Exception)
{
throw;
}
finally
{
if(connection.State == ConnectionState.Open)
{
connection.Close();
}
}
When running this code i had an error when openning the connection
Unable to connect to any of the specified MySQL hosts.
You are mixing MySQL and MSSQL.
Are you sure you want to connect to a MySQL server? Use http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection(v=vs.110).aspx if you would like to connect to MSSQL.
Also you should make yourself familiar with SQL injection

Informix database via odbc connection - Issue with insert stored procedure

This stored proc. - SP_insertinfo inserts an entry into a table.
I am connecting via an ODBC DSN to an informix database.
This is my code, this one doesn't throw me an error or doesn't insert a record.
I am connected via sequeLink 3.10 32-bit driver, my application runs on 64-bit OS.
Trying to identify why the data is not getting inserted(when i put a breakpoint, get the parameterized statement into the actual DB, there it inserts for the same data, however it fails when run from the application code).
int rowsInserted = command.ExecuteNonQuery(); //This line is always
returning -1 and data doesn't get inserted.
Any thoughts/idea will be very much helpful?
private void InsertInfo()
{
try
{
using(var connection = new OdbcConnection("dsn=mydsn;UID=myusername;PWD=****;"))
{
var command = connection.CreateCommand();
command.CommandType = CommandType.StoredProcedure;
command.Connection = connection;
command.CommandText = "execute procedure SP_insertinfo(?,?)";
command.Parameters.Clear();
//Insert parameter values
var paramId = new OdbcParameter("ID", OdbcType.Int) { Value = Convert.ToInt32(txtID.Text.Trim()) };
command.Parameters.Add(paramId);
var paramCountry = new OdbcParameter("Country", OdbcType.VarChar, 25) { Value = txtCountry.Text.Trim() };
command.Parameters.Add(paramCountry);
connection.Open();
int rowsInserted = command.ExecuteNonQuery(); //This line is always returning -1 and data doesn't get inserted.
if (rowsInserted > 0)
{
MessageBox.Show("Insert data saved.");
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString()) ;
}
}
At first try to execute your procedure as simple statement, not as prepared statement. This will look like:
command.CommandText = "execute procedure SP_insertinfo(1, 'Poland')";
connection.Open();
int rowsInserted = command.ExecuteNonQuery();
This way you will see if it is problem with prepared statement.
Try to execute execute procedure SP_insertinfo(1, 'Poland') via dbaccess (Informix tool). This way you will see if it is ODBC issue.
If it do not work with dbaccess then you will have to debug SP_insertinfo. If it work, then problem is with ODBC. Then I suggest enabling ODBC trace in ODBC Manager and analyzing log it will produce.
After a long research, i found out that, in order for ODBC dsn to work correctly with sequeLink, the drivers should match the version of operating system, i am using windows 7.0 64-bit, my dsn was 32-bit , i used a 64-bit dsn in order to work with 64-bit OS.

MySQL ODBC Parameter issue

Okay, so I'm getting a weird error with this function.
It's saying:
Exception Details: System.Data.Odbc.OdbcException: ERROR [HY000] [MySQL][ODBC 5.1 Driver][mysqld-5.0.27-community-nt]Column 'CommentNumber' cannot be null
But I can verify that the variable commentnumber is indeed getting a value. If I put a Response.Write right before the
command.Parameters.Add("#CommentNumber", commentnumber);"
line I get 1 returned (which is correct).
public string commenter(string commentnumber, string postnumber, string commentname, string commentemail, string comment) {
OdbcConnection connection = new OdbcConnection();
connection.ConnectionString = "server=<address>;"
+ "database=<database>;"
+ "uid=<username>;"
+ "password=<password>;"
+ "DRIVER={MySQL ODBC 5.1 Driver}";
string CommandText = "INSERT INTO Comments (CommentNumber, PostNumber, Name, Email, PostTime, Comment) VALUES (#CommentNumber, #PostNumber, #Name, #Email, #PostTime, #Comment)";
connection.Open();
try {
OdbcCommand command = new OdbcCommand(CommandText, connection);
command.Parameters.Add("#CommentNumber", commentnumber);
command.Parameters.Add("#PostNumber", postnumber);
command.Parameters.Add("#Name", commentname);
command.Parameters.Add("#Email", commentemail);
command.Parameters.Add("#PostTime", DateTime.Now);
command.Parameters.Add("#Comment", comment);
command.ExecuteNonQuery();
command.Dispose();
command = null;
}
catch(Exception ex) {
// Response.Write("There's been a problem. Please contact technical support.");
throw new Exception(ex.ToString(), ex);
Response.End();
}
finally {
connection.Close();
}
return "Success!";
}
ODBC uses ? for placholders. Since you're using #CommandNumber in the raw sql string, it's actually being interpreted by MySQL as an undefined server-side variable, hence the "cannot be null" error.
The second parameter is the OdbcType, not the value. Try using .AddWithValue()
What type is the field CommentNumber?.
Specifies the type of the parameter to add command.Parameters

How to execute a update statement using Oracle ODP.Net in C#

I am using Oracle.DataAccess.Client to work with Oracle database in my ASP.Net application. There is no help documentation in MSDN for ODP.Net and Oracle's documentation is really really bad. I am not able find the answer to this simple question.
Is it not possible to execute a simple update statement without having to build a dataset object and updating the dataset?
How to execute an update statement using Oracle ODP.Net in C#?
I will need to check the exact syntax, but here is some quick code off the top of my head
using (OracleConnection con = new OracleConnection(...))
{
con.Open();
OracleCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update table set col1 = :param1, col2 = :param2 where key = :keyValue";
cmd.Parameters.AddWithValue("param1", 1);
cmd.Parameters.AddWithValue("param2", "Text data");
cmd.Parameters.AddWithValue("keyValue", "1");
cmd.ExecuteNonQuery();
}
The above creates a command object sets the command up to execute an SQL Update statement, in this example I show one way to setup a parameterized query, you should always go with a parameterized query. Once the command is setup you just call ExecuteNonQuery to actually execute the command.
So after a bit of sleuthing and working this one out for a while, I found that the method I used to add a new parameter to the connection command is as follows. I did not find the method as was stated in the previous post. Mind you I am using a query object that I am passing the values around with.
public Boolean InsertMethod(Query _query)
{
var success = false;
var queryString = string.Format(#"INSERT INTO TABLE(ID, OWNER, TEXT) VALUES (TABLE_SEQ.NEXTVAL,:OWNER, :TEXT)");
try
{
using (OracleConnection con = new OracleConnection(ConString))
{
con.Open();
OracleCommand cmd = con.CreateCommand();
cmd.CommandText = queryString;
cmd.Parameters.Add("OWNER", _query.Owner);
cmd.Parameters.Add("TEXT", _query.Text);
int rowsUpdated = cmd.ExecuteNonQuery();
if (rowsUpdated > 0) success = true;
}
return success;
}
catch (Exception ex)
{
log.Error(ex);
throw;
}
}
Further to #Chris's answer, here is the documentation page of OracleParameter class which has sample code on using OracleCommand to execute Updates.
EDIT: Here is the entry point for ODP.net documentation.

Can't connect to database (OCIenVCreate has failed)

I'm using an Oracle database(10g) which contains a stored procedure called Foo.
Foo takes 2 datetime as IN parameters and 1 cursor as OUT parameter. I've been trying to make the connection and the query to the database with the OleDbCommand, but since Foo needs a cursor I have no choice but to use a OracleCommand(right?).
When I try to connection to the database I get the following error : "OCIenvCreate has failed return code -1". I've gived the correct permissions to ASPNET user for the oci.dll file so that it can read and execute it. Unfortunately, I still get the same error and I'm lost.
Here is what cause the error
OracleConnectionStringBuilder conBuilder = new OracleConnectionStringBuilder();
conBuilder.DataSource = dataSrc;
conBuilder.UserID = user;
conBuilder.Password = password;
OracleConnection con = new OracleConnection(conBuilder.ConnectionString);
OracleCommand cmd = new OracleCommand("foo", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("this_is_a_cursor", OracleType.Cursor).Direction = ParameterDirection.Output;
con.Open(); // Cause the error at runtime
OracleDataReader reader = cmd.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
con.Close();
I've noticed that some other people are having the same problem.
I'm running the application from a Windows Server 2003 Entreprise Edition(I hope this can help).
Thank you.
I'm not quite sure what the exact problem was, but I managed to connect to my database with another provider in the connection string.

Categories

Resources