I can not insert variables from C # to MySql Database - c#

I have a database with the infos of the buyers of my product, but I would like it to send the value provided by the program to the database, if it is null, how can I do this?
Code:
I have a database with the infos of the buyers of my product, but I would like it to send the value provided by the program to the database, if it is null, how can I do this?
Code:
string comando = "SELECT COUNT(*) FROM tbl_usuario WHERE user=#Usuario AND pw=#Senha AND tipo=1";
var connection = new MySqlConnection(connString);
var cmd = new MySqlCommand(comando, connection);
cmd.Parameters.AddWithValue("#Usuario", usuario);
cmd.Parameters.AddWithValue("#Senha", senha);
var command = connection.CreateCommand();
connection.Open();
MySqlDataReader leitor = cmd.ExecuteReader();
while (leitor.Read())
{
hd_id = leitor["id"].ToString();
}
if (hd_id == null)
{
//Code i need here
}
int retorno = Convert.ToInt32(cmd.ExecuteScalar());
connection.Close();

There is quite a bit that has been lost in translation in this question, but from I think I am reading I think you want the ID from the database to be retrieved. But the query is just running a count command which will not contain that.
string comando = "SELECT COUNT(*) FROM tbl_usuario WHERE user=#Usuario AND pw=#Senha AND tipo=1";
should actually be
string comando = "SELECT id FROM tbl_usuario WHERE user=#Usuario AND pw=#Senha AND tipo=1";
As you are only returning 1 value (or null if no record match) then you do not need to use a reader; and you can read the return directly, and check for null
var sqlReturn = cmd.ExecuteScalar();
if (sqlReturn == null) { /* Code i need here */ }
else { hd_id = (int)sqlReturn; }
If I did not understand the question; please feel free to let me know and we'll see if we can get you fixed up.

C#
cmd.Parameters.AddWithValue("#Usuario", String.IsNullOrEmpty(usuario) ? DBNull.Value : usuario);
cmd.Parameters.AddWithValue("#Senha", String.IsNullOrEmpty(senha) ? DBNull.Value : senha);

Related

Remove "" from string or in SQL varchar

Is it even possible to return value of string without the " " ?
I have the following string: Chb = "NOT";
Now i either want to remove the "" in C# or SQL.
so i want to have either Chb = NOT in C#
,or i want to remove the ' ' in SQL that i get in #Chb so that this:
WHERE PAR #Chb IN ('1','2','3')
isnt like this : WHERE PAR 'NOT' IN ('1','2','3')
but it is like this WHERE PAR NOT IN ('1','2','3')
I don't believe this is the right approach for this.
If you want to execute a command in SQL which comes from a C# code, then i would do:
string exists = "select * from table where var in (1,2,3)";
string notExists = "select * from table where var NOT in (1,2,3)";
if (chb != "NOT")
{
SqlCommand cmd = new SqlCommand(exists, con);
cmd.ExecuteScalar();
}
else
{
SqlCommand cmd = new SqlCommand(notExists, con);
cmd.ExecuteScalar();
}

"Select count()" returns wrong value

I am trying to determine if a specific value exists in a Oracle database table.
I used a query with "select count(*)", "select count(1)" and select count(<col_name>)" but keep getting the wrong result. When I use SQL Developer and run the query I get zero for the count. However, in the DAL, I get 1. I am guessing it is returning the number of row rather than the count itself. I tried both executeScalar() and ExecuteReader().
public override bool zipExists(string sZipCode)
{
OracleConnection conn = new OracleConnection(this.OraDataConnectionString);
OracleCommand oraCmd = new OracleCommand();
decimal iNumEntries = 0;
string sQuery = "select count(ZIPCODEID) as ZipCount from ZIPCODE where ZIPCODE = :ZipCode";
SetOraCommandType(oraCmd, CommandType.Text, sQuery);
conn.Open();
oraCmd.Connection = conn;
oraCmd.BindByName = true;
AddParamToOraCmd(oraCmd, "ZipCode", OracleDbType.Varchar2, 11, ParameterDirection.Input, sZipCode);
using (OracleConnection cn = new OracleConnection(this.OraDataConnectionString))
{
oraCmd.Connection = cn;
cn.Open();
iNumEntries = (decimal)oraCmd.ExecuteScalar();
}
return iNumEntries > 0;
also tried:
OracleDataReader sqlReader = oraCmd.ExecuteReader();
try
{
if (sqlReader.Read())
{
if (sqlReader["ZipCount"] != DBNull.Value)
iNumEntries = Convert.ToInt16(sqlReader["ZipCount"]);
}
}
}
return iNumEntries > 0;
I try you code on my table but pointing to some column and giving a select count(EN_Qty) as ZipCount from PSLAT.FSDEV.dbo.PS_EN_GEN_INTFC_BI where EN_Qty = '2600' works on my end so where in the code exactly are you experiencing an issue..? fyi I replaced my table with your query and assigned a value to the where clause.. so you query looks right.. however I would do an order by query to see if you perhaps are missing a zipcode..also oraCmd.ExecuteScalar() returns only 1 row so make sure you are not returning more than one row..oracle is funny like that
change your code to the following
object bExists = oraCmd.ExecuteScalar();
var bexists = bExists != DBNull.Value && result != null;
or change your code to check for row.count > 0 if true then you know the zipcode was found. Remember when making changes to Sql scripts or stored procedures in Oracle, you need to Compile the changes otherwise the changes will be visible to you when looking at the code but not to the caller trying to execute the stored proc.

cek valid data in table with input ";" and where in

i want to check valid data...
i have a table Divisi with sample data like this:
=====================
IdDivisi NamaDivisi
=====================
1 DivisiA
2 DivisiB
3 DivisiC
in my code, i get value :
string data = DivisiA;DivXXX
so, when checked, the alert will appear invalid data.
I want to get a query like this:
select NamaDivisi from Divisi where NamaDivisi IN('DivisiA','DivXXX')
and the result is null or empty or invalid.
because there are values ​​/ data 'DivXXX' is not valid on the table Divisi
But this time, when I debug, I get the query result like this:
select NamaDivisi from Divisi where NamaDivisi IN ('DivisiA;DivXXX')
===================================================
This is the full code.
private string CekValidDivisi(string data)
{
DivisiFacade div = new DivisiFacade();
string getDivisi = div.CekValidData(data);
return getDivisi;
}
public string CekValidData(string data)
{
SqlConnection Conn = DataSetting.GetSqlConnection();
SqlCommand Comm = new SqlCommand();
try
{
Conn.Open();
string sql = #"select NamaDivisi from Divisi where NamaDivisi IN('" + data + "')";
Comm = new SqlCommand(sql, Conn);
data = Convert.ToString(Comm.ExecuteScalar());
}
finally
{
Conn.Close();
Conn.Dispose();
}
return data;
}
please help me to resolve the problem in my code. thank you ...
You have multiple problems in your code, but this is not a place to teach you basics, so I'll try to stick to the topic. If you want to have a parameter like that, you have to create it like that first. I guess the data contains string with value DivisiA;DivXXX (and I presume DivXXX is just a generic name meaning you have multiple divisions there). Probably the easiest way would be to do something like this with it
public string CekValidData(string data)
{
SqlConnection Conn = DataSetting.GetSqlConnection();
SqlCommand Comm = new SqlCommand();
try
{
Conn.Open();
string paramData = ParseData(data);
string sql = #"select NamaDivisi from Divisi where NamaDivisi IN('" + paramData + "')";
Comm = new SqlCommand(sql, Conn);
data = Convert.ToString(Comm.ExecuteScalar());
}
finally
{
Conn.Close();
Conn.Dispose();
}
return data;
}
private string ParseData(string data)
{
return data.Replace(";", "','");
}
Haven't tried it, but hope you get the idea. Either way, please for your own sake, do some research on what is the best way to handle sql connections in c# and also how to prevent SQL injections.

string returns assigned value instead of database data

I try to receive a nickname from an user from the database, but it always returns the value which is assigned to the string nickname variable.
public string GetEigenaarBlog(int gebruikerid)
{
string nickname = null;
try
{
connection.Open();
string sql = "SELECT Nickname FROM Gebruiker WHERE GebruikerID = :gebruikerid";
command = new OracleCommand(sql, connection);
command.Parameters.Add(new OracleParameter("gebruikerid", gebruikerid));
nickname = Convert.ToString(command.ExecuteReader());
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
connection.Close();
}
return nickname;
}
This is my code in the form:
private void listBoxBerichten_SelectedIndexChanged(object sender, EventArgs e)
{
ListBox lb = (ListBox)sender;
Blog blog = (Blog)lb.Items[lb.SelectedIndex];
int blogid = blog.BlogID;
geselecteerdeBlog = dk.GetGeselecteerdeBlog(blogid);
string blogeigenaar;
foreach (Blog b in geselecteerdeBlog)
{
blogeigenaar = dk.GetEigenaarBlog(b.GebruikerID); //This is the method where is the problem
tbGeblogd.Text = Convert.ToString(b.Datum);
tbTitel.Text = b.Titel;
tbDoor.Text = blogeigenaar;
tbBlogInhoud.Text = b.Inhoud;
}
}
The parameter works, it reads that parameter from the form.
When I change string nickname = null to string nickname = 'hello' then it returns nickname as hello. So it returns the assigned value. When I keep string nickname = null then it returns null
What am I doing wrong? the SQL-query is right, and the user exist in the database. I'm not getting any errors or warnings.
Thanks!
Your code needs to be changed in this way
public string GetEigenaarBlog(int gebruikerid)
{
string nickname = null;
try
{
connection.Open();
string sql = "SELECT Nickname FROM Gebruiker WHERE GebruikerID = :gebruikerid";
command = new OracleCommand(sql, connection);
command.Parameters.Add(new OracleParameter("gebruikerid", gebruikerid));
OracleDataReader reader = command.ExecuteReader();
// Now try to read from the reader (and position the reader on the first record returned)
if(reader.Read())
nickname = reader[0].ToString();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
connection.Close();
}
return nickname;
The ExecuteReader method returns an OracleDataReader and this object needs to be positioned on the first record before trying to read from it. Thus you need to call the Read method, and if that method returns true you could read the string.
Said that however, when you have a query that returns just one row and one column then a very fast approach is through the ExecuteScalar method
connection.Open();
string sql = "SELECT Nickname FROM Gebruiker WHERE GebruikerID = :gebruikerid";
command = new OracleCommand(sql, connection);
command.Parameters.Add(new OracleParameter("gebruikerid", gebruikerid));
// ExecuteScalar returns the value of the first row/first column, or null if
// there is no record to return. Need to be carefull here
object result = command.ExecuteScalar();
if(result != null)
nickname = result.ToString();
As a side note, I can't see the full code, but it seems that you keep a global connection object.
This is considered a bad and needless practice because the Connection Pooling mechanism could do a better work to keep the connection objects ready to use
You cannot access a datareader this way. You will have to loop through the datareader and get the data. See http://msdn.microsoft.com/en-us/library/system.data.oracleclient.oracledatareader.aspx for more info.
Instead of
nickname = Convert.ToString(command.ExecuteReader());
try this
OracleDataReader reader = command.ExecuteReader();
nickname = "";
while (reader.Read())
{
nickname = Convert.ToString(reader[0]));
}

Handling ExecuteScalar() when no results are returned

I am using the following SQL query and the ExecuteScalar() method to fetch data from an Oracle database:
sql = "select username from usermst where userid=2"
string getusername = command.ExecuteScalar();
It is showing me this error message:
System.NullReferenceException: Object reference not set to an instance of an object
This error occurs when there is no row in the database table for userid=2.
How should I handle this situation?
According to MSDN documentation for DbCommand.ExecuteScalar:
If the first column of the first row in the result set is not found, a
null reference (Nothing in Visual Basic) is returned. If the value in
the database is null, the query returns DBNull.Value.
Consider the following snippet:
using (var conn = new OracleConnection(...)) {
conn.Open();
var command = conn.CreateCommand();
command.CommandText = "select username from usermst where userid=2";
string getusername = (string)command.ExecuteScalar();
}
At run-time (tested under ODP.NET but should be the same under any ADO.NET provider), it behaves like this:
If the row does not exist, the result of command.ExecuteScalar() is null, which is then casted to a null string and assigned to getusername.
If the row exists, but has NULL in username (is this even possible in your DB?), the result of command.ExecuteScalar() is DBNull.Value, resulting in an InvalidCastException.
In any case, the NullReferenceException should not be possible, so your problem probably lies elsewhere.
First you should ensure that your command object is not null. Then you should set the CommandText property of the command to your sql query. Finally you should store the return value in an object variable and check if it is null before using it:
command = new OracleCommand(connection)
command.CommandText = sql
object userNameObj = command.ExecuteScalar()
if (userNameObj != null)
string getUserName = userNameObj.ToString()
...
I'm not sure about the VB syntax but you get the idea.
I just used this:
int? ReadTerminalID()
{
int? terminalID = null;
using (FbConnection conn = connManager.CreateFbConnection())
{
conn.Open();
FbCommand fbCommand = conn.CreateCommand();
fbCommand.CommandText = "SPSYNCGETIDTERMINAL";
fbCommand.CommandType = CommandType.StoredProcedure;
object result = fbCommand.ExecuteScalar(); // ExecuteScalar fails on null
if (result.GetType() != typeof(DBNull))
{
terminalID = (int?)result;
}
}
return terminalID;
}
The following line:
string getusername = command.ExecuteScalar();
... will try to implicitly convert the result to string, like below:
string getusername = (string)command.ExecuteScalar();
The regular casting operator will fail if the object is null.
Try using the as-operator, like this:
string getusername = command.ExecuteScalar() as string;
sql = "select username from usermst where userid=2"
var _getusername = command.ExecuteScalar();
if(_getusername != DBNull.Value)
{
getusername = _getusername.ToString();
}
Check out the example below:
using System;
using System.Data;
using System.Data.SqlClient;
class ExecuteScalar
{
public static void Main()
{
SqlConnection mySqlConnection =new SqlConnection("server=(local)\\SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI;");
SqlCommand mySqlCommand = mySqlConnection.CreateCommand();
mySqlCommand.CommandText ="SELECT COUNT(*) FROM Employee";
mySqlConnection.Open();
int returnValue = (int) mySqlCommand.ExecuteScalar();
Console.WriteLine("mySqlCommand.ExecuteScalar() = " + returnValue);
mySqlConnection.Close();
}
}
from this here
SQL NULL value
equivalent in C# is DBNull.Value
if a NULLABLE column has no value, this is what is returned
comparison in SQL: IF ( value IS NULL )
comparison in C#: if (obj == DBNull.Value)
visually represented in C# Quick-Watch as {}
Best practice when reading from a data reader:
var reader = cmd.ExecuteReader();
...
var result = (reader[i] == DBNull.Value ? "" : reader[i].ToString());
In my experience, there are some cases the returned value can be missing and thus execution fails by returning null. An example would be
select MAX(ID) from <table name> where <impossible condition>
The above script cannot find anything to find a MAX in. So it fails. In these such cases we must compare the old fashion way (compare with C# null)
var obj = cmd.ExecuteScalar();
var result = (obj == null ? -1 : Convert.ToInt32(obj));
If you either want the string or an empty string in case something is null, without anything can break:
using (var cmd = new OdbcCommand(cmdText, connection))
{
var result = string.Empty;
var scalar = cmd.ExecuteScalar();
if (scalar != DBNull.Value) // Case where the DB value is null
{
result = Convert.ToString(scalar); // Case where the query doesn't return any rows.
// Note: Convert.ToString() returns an empty string if the object is null.
// It doesn't break, like scalar.ToString() would have.
}
return result;
}
Always have a check before reading row.
if (SqlCommand.ExecuteScalar() == null)
{
}
This is the easiest way to do this...
sql = "select username from usermst where userid=2"
object getusername = command.ExecuteScalar();
if (getusername!=null)
{
//do whatever with the value here
//use getusername.toString() to get the value from the query
}
In your case either the record doesn't exist with the userid=2 or it may contain a null value in first column, because if no value is found for the query result used in SQL command, ExecuteScalar() returns null.
Alternatively, you can use DataTable to check if there's any row:
SqlCommand cmd = new SqlCommand("select username from usermst where userid=2", conn);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adp.Fill(dt);
string getusername = "";
// assuming userid is unique
if (dt.Rows.Count > 0)
getusername = dt.Rows[0]["username"].ToString();
private static string GetUserNameById(string sId, string connStr)
{
System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(connStr);
System.Data.SqlClient.SqlCommand command;
try
{
// To be Assigned with Return value from DB
object getusername;
command = new System.Data.SqlClient.SqlCommand();
command.CommandText = "Select userName from [User] where userid = #userid";
command.Parameters.AddWithValue("#userid", sId);
command.CommandType = CommandType.Text;
conn.Open();
command.Connection = conn;
//Execute
getusername = command.ExecuteScalar();
//check for null due to non existent value in db and return default empty string
string UserName = getusername == null ? string.Empty : getusername.ToString();
return UserName;
}
catch (Exception ex)
{
throw new Exception("Could not get username", ex);
}
finally
{
conn.Close();
}
}
Slight conjecture: if you check the stack for the exception, it is being thrown then the ADO.NET provider for Oracle is reading the underlying rowset to get the first value.
If there is no row, then there is no value to find.
To handle this case execute for a reader and handle Next() returning false for the case of no match.
I Use it Like This with Microsoft Application Block DLL (Its a help library for DAL operations)
public string getCopay(string PatientID)
{
string sqlStr = "select ISNULL(Copay,'') Copay from Test where patient_id=" + PatientID ;
string strCopay = (string)SqlHelper.ExecuteScalar(CommonCS.ConnectionString, CommandType.Text, sqlStr);
if (String.IsNullOrEmpty(strCopay))
return "";
else
return strCopay ;
}
I have seen in VS2010
string getusername = command.ExecuteScalar();
gives compilation error,
Cannot implicitly convert type object to string.
So you need to write
string getusername = command.ExecuteScalar().ToString();
when there is no record found in database it gives error
Object reference not set to an instance of an object
and when I comment '.ToString()', it is not give any error. So I can say ExecuteScalar not throw an exception. I think anserwer given by #Rune Grimstad is right.
I had this issue when the user connecting to the database had CONNECT permissions, but no permissions to read from the database. In my case, I could not even do something like this:
object userNameObj = command.ExecuteScalar()
Putting this in a try/catch (which you should probably be doing anyway) was the only way I could see to handle the insufficient permission issue.
object objUserName;
objUserName = command.ExecuteScalar();
if (objUserName == null) //if record not found ExecuteScalar returns null
{
return "";
}
else
{
if (objUserName == DBNull.Value) //if record found but value in record field is null
{
return "";
}
else
{
string getusername = objUserName.ToString();
return getusername;
}
}
/* Select some int which does not exist */
int x = ((int)(SQL_Cmd.ExecuteScalar() ?? 0));
I used this in my vb code for the return value of a function:
If obj <> Nothing Then
Return obj.ToString()
Else
Return ""
End If
Try this code, it appears to solve your problem.
Dim MaxID As Integer = Convert.ToInt32(IIf(IsDBNull(cmd.ExecuteScalar()), 1, cmd.ExecuteScalar()))
I'm using Oracle.
If your sql returns numeric value, which is int, you need to use Convert.ToInt32(object). Here is the example below:
public int GetUsersCount(int userId)
{
using (var conn = new OracleConnection(...)){
conn.Open();
using(var command = conn.CreateCommand()){
command.CommandText = "select count(*) from users where userid = :userId";
command.AddParameter(":userId", userId);
var rowCount = command.ExecuteScalar();
return rowCount == null ? 0 : Convert.ToInt32(rowCount);
}
}
}
Try this
sql = "select username from usermst where userid=2"
string getusername = Convert.ToString(command.ExecuteScalar());

Categories

Resources