I am trying to find sum of values in a column using a condition but the result am getting is null am not sure of where the problem is coz i have tried running the sql database access but and it works but when i it at in the progam it does not work
So i need assistance on this one
The code is below
Blockquote
p.Query="SELECT SUM(income) FROM Emp_income WHERE username ='" + frmlogin.username + "'";
using (IDbCommand command = new OleDbCommand(p.Query, p.Con))
{
object answer=command.ExecuteScalar();
lblincome.Text=Convert.ToString(answer);
}
Add try/catch block to ExcuteScalar() for error message, for connection oriented ADO.Net you have to Open connection before executing the command like con.Open()
Related
I've got the following
SqlCommand cmd = getSQLCommand();
using (cmd.Connection)
using (cmd)
{
try
{
string dbName = txt_DatabaseName.Text;
var createDatabaseQuery = "exec ('CREATE DATABASE ' + #databaseName)";
var sqlCommand = new SqlCommand(createDatabaseQuery, cmd.Connection);
sqlCommand.Parameters.Add("#databaseName", SqlDbType.Text);
sqlCommand.Parameters["#databaseName"].Value = dbName.ToString();
cmd.Connection.Open();
sqlCommand.ExecuteNonQuery();
}
catch (SqlException ex)
{
Console.WriteLine(ex.ToString());
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('SQL Error. Record not added.')", true);
}
finally
{
cmd.Connection.Close();
}
}
I'm fully aware that params are not supported in DDL operations, so I've got this really cool thread that I've been using to help me write the contents within the "try".
How to use SqlCommand to CREATE DATABASE with parameterized db name?
That said, I'm still getting an exception error for incorrect syntax near 'Database'. This might be a user error but I've been stuck around this for an hour or so now.
Any thoughts/ improvements?
p.s. All I'm trying to do is to create a database programmatically by using a dynamic value of whatever happens to be in txt_DatabaseName.Text (and yes I will try to error handle this in case there's white spaces entered or any chars that are not supported in SQL.
p.p.s Any articles that I can have a look at against sql injection attacks or any suggestions around constructing the method I have to prevent it? This is a simple exercise that I'm doing on my local machine, not public facing but still would like to get ahead of the game if possible.
You don't need the exec part at all. Again you are getting error after removing exec cause you are wrapping your query in single quote 'CREATE DATABASE ' which is getting considered as string literal. It should just be
var createDatabaseQuery = string.Format("CREATE DATABASE {0}",DBnamevariable);
var sqlCommand = new SqlCommand(createDatabaseQuery, cmd.Connection);
Take a look with the sql profiler to see what is being fired against the database. If it is not working try to execute the query in Management studio to see it that is working. It's probably some kind of special character that is not allowed.
I have tried various forms of the following method to get the next sequence value from an Oracle DB in my asp.net app. The sql statement works fine in Toad (11g). The sql statement includes "Select ... myschema.mySeq.nextval ... from dual. But the error I receive when I get to cmd.ExecuteNonQuery() -- the error is:
>
Exception Details: Oracle.DataAccess.Client.OracleException: ORA-00942: table or view does not exist
<<
Authentication is a very big deal at the place where I am at. Is this a data Access problem or is something incorrect with my method (below)? If something is incorrect with the code below what is the correction I need to make? Note: the app (big app) has hundreds of calls to SPs (which all work fine), so I basically copied the connection string code and used a constant (like they do throughout the app). If I use an SP this works, but I want to not use an SP just straight forward Ado.Net. What is the fix?
public int getNextPositionSequence(string userSeq)
{
OracleConnection conn = new OracleConnection(DaoHelper.GetConnectionString("AuthenticatedOracleConnectionString"));
conn.Open();
conn.ClientId = userSeq;
string sql = "SELECT ddtms.position_seq.nextval from dual";
OracleCommand cmd = new OracleCommand(sql, conn);
object s = cmd.ExecuteNonQuery(); //<<<--- crashes here
conn.Close();
return 1;
}
after connecting to database in C#
string MyConString2 = "SERVER=localhost;" + "user id=mytest;" + "DATABASE=clusters;" + "PASSWORD=mypass;";
I have an algorithm which I need to after each run of algorithm that will fill the database, drop the database "clusters" of mysql manually and again connect to the empty database and run it again,gaining new data in tables
I want to make it automatically how can I drop or empty my database if exists in C# and then run my algorithm?
Here is example code that works and I think this is what you are talking about, if not, feel free to correct me.
using (var connection = new MySqlConnection("server=localhost;user=root;password="))
{
connection.Open();
var command = connection.CreateCommand();
command.CommandText = "drop schema if exists clusters";
command.ExecuteNonQuery();
command = connection.CreateCommand();
command.CommandText = "create schema clusters";
command.ExecuteNonQuery();
}
Prepare sql query for clearing your DB and test it in f.e. MySQL workbench. Following this, just execute it as you would execute regular query against DB in C#. One way is to clear all the tables in your database by using TRUNCATE statement and the second way is to DROP DATABASE and recreate it.
In my C# application, I do the following:
using (SqlConnection connection = new SqlConnection(connectionstr))
{
connection.Open();
SqlCommand com1 = new SqlCommand("insert into Anfangstierbestand(bestand, jahr, loginid) VALUES (" + bestand + ", " + jahr + ", " + loginid + ");", connection);
SqlCommand com2 = new SqlCommand("select * from Anfangstierbestand;", connection);
com1.Connection = connection;
int ferksum = 0;
com1.ExecuteNonQuery();
connection.Close();
connection.Open();
SqlDataReader read = com2.ExecuteReader();
while (read.Read())
{
ferksum += Convert.ToInt32(read[2]);
}
// MessageBox.Show("Fehler beim Erstellen des Tierbestandes", "Fehler"); }
MessageBox.Show(ferksum.ToString());
}
It's a simple insert to a database. I added com2 to check, if the insert works.
Unfortunately, the the value of com2 tells me, that it works, but when I go to the Server Explorer and press Execute SQL, there are no new values.
I don´t know the reason. The code above is just an example, since a few days, no insert works anymore(before, the same code works).
Does anybody know what the reason can be?
EDIT:
C#:
string connectionstr = "Data Source=.\\SQLEXPRESS;" + "AttachDbFilename=|DataDirectory|\\Datenbank\\FarmersCalc.mdf;" + "Integrated Security=True;" + "User Instance=true;";
EDIT2:
Server Explorer:
Data Source=.\SQLEXPRESS;AttachDbFilename="C:\Users\user\Desktop\Farmer´s Calc\Programmierung\WPF\Finanz_WPF\Finanz_WPF\Datenbank\FarmersCalc.mdf";Integrated Security=True;User Instance=True
EDIT3:
Here are the columns:
id int,
jahr int,
anzahl int,
loginid int
EDIT4:
Is it possible that it´s a problem that I opened my project with expression blend? Normally, I work with VS 2010...
EDIT5:
Even because I can not answer my question(<100 reputations) I write it here:
Shame on me. Some of you were right, it was the wrong database-file. But I´m still wondering, why this happened, because I did not change anything since a few days and before this, it worked!
Thanks to all for helping!
You're using user instances, why? Isn't it possible that the instance you're connecting to in Server Explorer is not the same as the instance where your app is inserting data? What happens when you select data from within the app, does it reflect your insert(s)? It seems to me based on your connection strings that these are two completely different MDF files - they have the same name but they are in different locations.
Is the issue implicit transactions? Do you need to issue a commit of the SQL Insert? If com2 tells you that it's there then it may only see it since it's in the context of the current SQL transaction.
You should share your connection string for both Server Explorer and your SqlConnection (connectionstr). Ensure that you setup your Server Explorer connection with User Instance=true;.
As a diagnostic,
connection.Open();
int n = com1.ExecuteNonQuery();
// log or show 'n' , the nr of rows affected
Edit, after seeing the connectionstrings:
local db files in |DataDirectory|\ are very prone to be overwritten by the next run or build command.
Make sure you set them to 'copy never' or 'copy if newer' in the VS Solution explorer.
Perhaps somewhere in the callstack above this code, someone has added a TransactionScope.
This would cause the connections to enroll automatically in the transaction, and the connections could see the data inserted via that not-yet-committed transaction. When the scope is exitted without calling scope.Complete, the transaction gets rolled back and no data is saved.
I need to run a stored procedure from a C# application.
I use the following code to do so:
Process sqlcmdCall = new Process();
sqlcmdCall.StartInfo.FileName = "sqlcmd.exe";
sqlcmdCall.StartInfo.Arguments = "-S localhost\\SQLEXPRESS -d some_db -Q \":EXIT(sp_test)\""
sqlcmdCall.Start();
sqlcmdCall.WaitForExit();
From the sqlcmdCall object after the call completes, I currently get an ExitCode of -100 for success and of 1 for failure (i.e. missing parameter, stored proc does not exist, etc...).
How can I customize these return codes?
H.
I have a small VB.Net app that executes system commands like that. To capture error or success conditions I define regular expressions to match the error text output from the command and I capture the output like this:
myprocess.Start()
procReader = myprocess.StandardOutput()
While (Not procReader.EndOfStream)
procLine = procReader.ReadLine()
If (MatchesRegEx(errRegEx, procLine)) Then
writeDebug("Error reg ex: [" + errorRegEx + "] has matched: [" + procLine + "] setting hasError to true.")
Me.hasError = True
End If
writeLog(procLine)
End While
procReader.Close()
myprocess.WaitForExit(CInt(waitTime))
That way I can capture specific errors and also log all the output from the command in case I run across an unexpected error.
If you are trying to call a stored procedure from c# you would want to use ADO.Net instead of the calling sqlcmd via the command line. Look at SqlConnection and SqlCommand in the System.Data.SqlClient namespace.
Once you are calling the stored procedure via SqlCommand you will be able to catch an exception raised by the stored procedure as well we reading the return value of the procedure if you need to.
Even with windows authentication you can still use SqlCommand and SqlConnection to execute, and you don't have to re-invent the wheel for exception handling.
A simple connection configuration and a single SqlCommand can execute it without issue.