I'm trying create a class in C# for manipulate Mysql data
I can get datas with my methods but I can't update data, and no return nothing exceptions
I using this line for call my method
Email1.Text=bdOp.alterContent(Email1.Text, "Email");
Method 'alterContent':
public String alterContent(String valor, String nome)
{
String query = "update conteudo set conteudo = #valor where nome= #nome ";
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("#valor", valor);
cmd.Parameters.AddWithValue("#nome", nome);
try
{
conn.Open();
cmd.CommandText = query;
cmd.ExecuteNonQuery();
conn.Close();
return "Sucesso.";
}
catch (Exception erro) { return erro.ToString(); }
}
This method has return String, because I had using to check exceptions
I don't know why this code no update my data and no return any exceptions
I had a very similar situation last night... it was in MVC, so I had to stop the virtual localhost, and do a clean build. After restarting visual studio... it worked. I wasn't getting any error either.
Also, validate the text in Email.Text, perhaps something there might be triggering a problem.
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 write a C# program which uses a database, Matches.mdf.
I want to test the database file existence, using File.Exists routine (codes will come at the end of the question). If the file doesn't exist, the program creates a new database with the above name. To test the database existence routine, I renamed the database file, but when I wanted to create the database, I got the following error message: Database "Matches" already exists, please specify a different name.
At a second test, I used a database dropping routine before calling the creating routine. Big mistake. Every time I try to create the Matches.mdf database, I get the following error message:
I am sure that the cause of this error message is me, tinkering around, because the same database creation and deletion routines worked fine before.
I know I can solve the problem by changing the path of the database file, but I want to know what exactly I broke up here so I know for next time.
What I am asking is: what can I do to solve the above error?
Later edit: I tried to manually recreate the Matches.mdf using the query tool from SQL Server Object Explorer from VS 2019. Worked perfectly, but I don't think it's a good solution long term.
Necessary codes:
Variable declarations:
static readonly string DatabaseFolder = Path.GetDirectoryName(Application.ExecutablePath) + "\\db";
readonly string DatabaseFile = DatabaseFolder + "\\Matches.mdf";
readonly string DatabaseLog = DatabaseFolder + "\\MatchesLog.ldf";
The function that checks the database file existence:
public bool DatabaseExists()
{
return File.Exists(DatabaseFile);
}
The database creation routine:
private bool CreateDatabaseFile()
{
SqlConnection MyConn = new SqlConnection(CreateDatabaseConnectionString);
string Str = "Create Database Matches on Primary (Name=Matches, Filename='#DatabaseFile') log on (Name=MatchesLog, Filename='#DatabaseLog')";
SqlCommand DatabaseCreationCommand = new SqlCommand(Str, MyConn);
DatabaseCreationCommand.Parameters.Add("#DatabaseFile", SqlDbType.Text).Value = DatabaseFile;
DatabaseCreationCommand.Parameters.Add("#DatabaseLog", SqlDbType.Text).Value = DatabaseLog;
try
{
MyConn.Open();
DatabaseCreationCommand.ExecuteNonQuery();
}
catch (SqlException S)
{
MessageBox.Show(S.Message);
return false;
}
catch (IOException I)
{
MessageBox.Show(I.Message);
return false;
}
catch (InvalidOperationException I)
{
MessageBox.Show(I.Message);
return false;
}
catch (InvalidCastException I)
{
MessageBox.Show(I.Message);
return false;
}
finally
{
MyConn.Close();
}
return true;
}
The database deleting routine:
public void DeleteDatabase()
{
string Str;
SqlConnection MyConn = new SqlConnection(CreateDatabaseConnectionString);
Str = "Alter database Matches set single_user with rollback immediate\r\ndrop database Matches";
SqlCommand command = new SqlCommand(Str, MyConn);
try
{
MyConn.Open();
command.ExecuteNonQuery();
}
catch (SqlException S)
{
MessageBox.Show(S.Message);
}
catch (IOException I)
{
MessageBox.Show(I.Message);
}
catch (InvalidOperationException I)
{
MessageBox.Show(I.Message);
}
catch (InvalidCastException I)
{
MessageBox.Show(I.Message);
}
finally
{
MyConn.Close();
}
}
As it is said here and confirmed by Jeroen Mostert, Create database does not accept queries. The database was created before, using some string concatenation. Afterwards the query string was parametrized, without realizing that this command doesn't take parameters. This is why changing the creating database query to
Create Database Matches
works perfectly.
Well, live and learn!
I tried to find a useful answer to this question, but failed (the closest I found was this). I have a C# app calling a stored procedure which uses SQL TRY/CATCH to handle errors. I can replicate the issue with a sample stored procedure like this:
if object_id('dbo.TestSQLError') is not null drop proc dbo.TestSQLError
go
create proc dbo.TestSQLError
as
begin try
select 1 / 0
end try
begin catch
raiserror('Bad tings appen mon', 16, 1)
end catch
then a little dummy program like this:
namespace TestSQLError
{
class Program
{
public const string CONNECTION_STRING = #"data source=localhost\koala; initial catalog=test; integrated security=true;";
static void Main(string[] args)
{
try
{
using (SqlConnection conn = new SqlConnection(CONNECTION_STRING))
{
SqlCommand cmd = new SqlCommand("dbo.TestSQLError", conn) { CommandType = System.Data.CommandType.StoredProcedure };
conn.Open();
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
Console.WriteLine(rdr.GetValue(0).ToString());
}
rdr.Close();
}
conn.Close();
}
Console.WriteLine("Everything looks good...");
}
catch (SqlException se)
{
Console.WriteLine("SQL Error: " + se.Message);
throw se;
}
catch (Exception e)
{
Console.WriteLine("Normal Error: " + e.Message);
throw e;
}
Console.ReadLine();
}
}
}
The stored procedure raises an error of level 16 which as far as I've read should be enough to be error-worthy. However control never jumps to the catch block; it just chugs through like nothing went wrong.
I read someone suggest using OUTPUT parameters... which I can do, but it seems like I must be missing something fundamental and simple here. Can anyone help?
UPDATE: It would appear if I use ExecuteNonQuery() the errors propagate just fine. However my use case is a procedure which performs DML and returns data based on that DML. Maybe the answer is "don't do that" but it'd be nice to know if there's a way to simply catch an error when grabbing results.
The reason is because the raise error is after the end of the first result set in the data reader and we’ll only get the error if we call NextResult() on the data reader!
When using a SqlDataReader it will only iterate over the first result
set, which in this case will be the select in the stored procedure
Try and see more details here
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (!rdr.IsClosed())
{
while (rdr.Read())
{
Console.WriteLine(rdr.GetValue(0).ToString());
}
if (!rdr.NextResult())
{
rdr.Close();
}
}
}
I can make three suggestions:
Use CommandType.Text instead of CommandType.StoredProcedure. This may be fixed now, but a number of years ago I found that CommandType.StoredProcedure would always buffer message outputs into batches of about 50, while CommandType.Text would allow the messages to come back to C# right away.
Add a WITH NOWAIT hint to your RAISERROR code.
Don't forget about the FireInfoMessageEventOnUserErrors property. You do want to handle the InfoMessage event.
I'm not sure any of these will solve your problem, but they should give you some direction.
No exceptions, everything gets executed but the update doesn't happen!
Everything works ok when I have just #JIR parameter but now I added #Paragon and the update doesn't do it's job. No exception whatsoever data passed is OK...
I don't see anything wrong with this query does anyone know what could possibly be going wrong?
private static void InsertJIR(FisDnevni racun)
{
using (OleDbConnection con = new OleDbConnection(RegistarBlagajna.Modul.VezaNaBazu.ConnectionString))
{
try
{
con.Open();
OleDbCommand cmd = new OleDbCommand(#"
UPDATE FisDnevni
SET [JIR] = #JIR,
[Paragon] = #Paragon
WHERE BrojRacuna = #BrojRacuna"
, con);
cmd.Parameters.AddWithValue("#JIR", racun.JIR.Substring(0,37));
cmd.Parameters.AddWithValue("#BrojRacuna", racun.BrojRacuna);
cmd.Parameters.AddWithValue("#Paragon", racun.Paragon);
cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception)
{
throw;
}
}
}
This is a good old problem - ensure the query parameters in OleDbParameter are declared in proper order like this:
using (OleDbConnection con = new OleDbConnection(RegistarBlagajna.Modul.VezaNaBazu.ConnectionString))
{
try
{
con.Open();
using (OleDbCommand cmd = new OleDbCommand(#"UPDATE FisDnevni SET [JIR] = #JIR, [Paragon] = #Paragon WHERE BrojRacuna = #BrojRacuna", con)
{
cmd.Parameters.AddWithValue("#JIR", racun.JIR.Substring(0,37));
// this must be the second parameter instead of third one
cmd.Parameters.AddWithValue("#Paragon", racun.Paragon);
cmd.Parameters.AddWithValue("#BrojRacuna", racun.BrojRacuna);
cmd.ExecuteNonQuery();
con.Close();
}
}
catch (Exception)
{
throw;
}
}
Note that OLE DB .NET Provider doesn't recognize named parameters for OleDbCommand when CommandType is set to Text, but it apparently does recognize the parameter order, hence as long as they're passed in proper order, it'll accepted as query parameter.
Related issue:
how to update a table using oledb parameters?
maybe i've just never used it, but why is there an # here?
OleDbCommand(#"
i also havent worked with C# in a while but is multi-line concatenation possible without a + or something?
thirdly why are you using [] on these column names? i don't see any special characters or spaces.
this post is sounding a lot more dikkish than i mean it to be, im not trying, just legit curious
So what i am looking to do is use a web service call to implement an oracle procedure. To be more specific: I what it so that when i put a value into a parameter in my web service and run it, i want that to be the value sent to the procedure in oracle and then after successfully running to return to the web service as true.
What i have currently tried to to is this:
public bool InsertMachineModels(string MachineModel)
{
logger.DebugFormat("FilteredReportInputsDAO.InsertMachineModel({0})", MachineModel);
bool retVal = true;
using (OracleConnection conn = new OracleConnection(connectionString))
{
using (OracleCommand cmd = new OracleCommand("Admin_Utilities.InsertMachineModel", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("pMachineModel", OracleType.Cursor).Value = Convert.ToString(MachineModel);
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
if (IsErrorLogging)
logger.Error("FilteredReportInputsDAO.InsertMachineModels() Exception: ", ex);
retVal = false;
}
finally
{
conn.Close();
}
}
}
return retVal;
}
Below you will find my procedure which runs correctly when implemented in sql developer.
procedure InsertMachineModel( pMachineModel in nvarchar2)
is
begin
insert into machine_models (Machine_model) values (pMachineModel);
commit;
Exception when others then
pb_util.logdata(1, 'Admin_utilities.InsertMachineModel', 'Exception thrown', sqlerrm || ' stack ' || dbms_utility.format_error_backtrace);
rollback;
raise;
end;
What i believe to be the problem is this line in the web service:
cmd.Parameters.Add("pMachineModel", OracleType.Cursor).Value = Convert.ToString(MachineModel);
In my logger it says that a cursor must be implemented as a parameterdirection.output parameter however i do not believe in that case you can take a value and send it to the api, but if i am wrong feel free to correct me.
So i guess my question is: If what i believe to be correct in the statement above about parameterdirection is wrong, what is the correct answer?
Can anyone give me any suggestions as to how to implement what i am attempting to do correctly?
Any help or suggestions are greatly appreciated. Thank you.
I think your problem is in this line:
cmd.Parameters.Add("pMachineModel", OracleType.Cursor).Value =
Convert.ToString(MachineModel);
You're attempting to add a parameter of type OracleType.Cursor, which isn't correct or necessary. Try changing the line to this:
cmd.Parameters.Add("pMachineModel", OracleType.Char).Value = MachineModel;
(There's also no need for Convert.ToString here - MachineModel is already a String).