I have a method like this
private string AccountCreation()
{
string accountId="";
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
connection.Open();
SqlCommand command = new SqlCommand();
command.Connection = connection;
StringBuilder sql = new StringBuilder();
sql.AppendLine("SELECT ACCOUNT_ID,CUSTOMER_ID FROM T_ACCOUNT order by ACCOUNT_ID desc");
sql.AppendLine("SET IDENTITY_INSERT T_ACCOUNT ON");
sql.AppendLine("INSERT INTO T_ACCOUNT (ACCOUNT_ID,CUSTOMER_ID)");
sql.AppendLine("SELECT ACCOUNT_ID + 1, CUSTOMER_ID +1 FROM T_ACCOUNT Where ACCOUNT_ID = (select max(ACCOUNT_ID) from T_ACCOUNT)");
sql.AppendLine("SET IDENTITY_INSERT T_ACCOUNT OFF");
accountId = Convert.ToString(sql.AppendLine("SELECT top 1 ACCOUNT_ID FROM T_ACCOUNT order by ACCOUNT_ID desc"));
string strUpdateQuery = sql.ToString();
ExecuteQuery(strUpdateQuery, command);
}
return accountId;
}
Now accountId is holding the query but not the value returned after execution of the query. I want the value in that string. Can anyone help me?
For getting value from the query. you need ExecuteScalar method.
object oRetVal = command.ExecuteScalar();
string accountId = string.Empty;
if(oRetVal != null)
{
accountId = oRetVal.ToString();
}
However, it is recommend to use store procedure.
I assume you are looking for the "TOP 1 Account_ID" from the query. What you have done there will not work (or give you what you want). You will need to either send in a output parameter to put the accountID in, or run fetch the data using datareader or dataset.
You'll have to bind the output of your ExecuteQuery to an object.
check if this returns any result and populates the accID.
var accID = ExecuteQuery(strUpdateQuery, command)
public string ExecuteQuery(string query,SqlCommand cmd)
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = query;
object i=cmd.ExecuteScalar();
return i.ToString();
}
After this just assign this to the accounted
accountId = ExecuteQuery(strUpdateQuery, command);
Related
Case: I'm trying execute a query in C# with MySql.Data.MySqlClient, which containts INSERT INTO, i'm getting an error(see below):
Database table:
What im trying to achieve: I want to insert into a new record with: "value_id(Auto Increment)", "machine_id" "tag_name", "int_value", "real_value" and "bool_value";
I have the following code:
*Retrieving machine ID
private void getMachineID()
{
string connStr = "";
string ipAdressID = "'" + machineIP + "'";
string basicQueryID = "SELECT machine_id FROM machine WHERE machine.machine_ip LIKE ";
string totalQueryID = basicQueryID + ipAdressID;
//Create connection
MySqlConnection conn = new MySqlConnection(connStr);
//Query command
MySqlCommand cmd = conn.CreateCommand();
//Assign string to query
cmd.CommandText = totalQueryID;
//Open connection
conn.Open();
//Get result ID from machine where IP adress = machineIP and write to machineID variable.
machineID = (int)(cmd.ExecuteScalar());
}
Code to insert into the record:
try
{
string connStr = "";
MySqlConnection conn = new MySqlConnection(connStr);
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "INSERT INTO waardes(machine_id, tag_name, int_value, real_value, bool_value) VALUES(#machineID, #tagName, #intValue, #doubleValue, #boolValue)";
cmd.Parameters.AddWithValue("#tagName", tagName);
cmd.Parameters.AddWithValue("#intValue", intValue);
cmd.Parameters.AddWithValue("#doubleValue", doubleValue);
cmd.Parameters.AddWithValue("#boolValue", boolValue);
cmd.Parameters.AddWithValue("#machineID", machineID);
conn.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Hope you guys can help!
There's no INSERT with where clause.
Take a look at this question: How to insert with where clause
Maybe, you can create an IF inside your app to verify your parameters before executing the INSERT statement.
Based on your query, I believe you need an UPDATE:
UPDATE waardes SET tag_name = #tagName,
int_value = #intValue, real_value = #doubleValue,
bool_value = #boolValue WHERE machine.machine_id LIKE %1%
Is this what you need?
you cannot use where in insert statement, because insert statement is used for adding new rows to table. you better use update statement.
There can be no Where clause used with Insert. However you can use Where when you are using Insert Into. In your statement I suppose you are missing the Select From before your Where clause.
Consider the example:
INSERT INTO tableNameDestination
SELECT feild(s),...
FROM tableNameSource
WHERE Condition
In your case:
INSERT INTO waardes(tag_name, int_value, real_value, bool_value) VALUES(#tagName, #intValue, #doubleValue, #boolValue) Select field1, field2, field3, field4 from machine WHERE machine.machine_id LIKE " + "'" + machineID + "'";
I have a C# property which is of data type bool and when it gets set, it becomes a True or False.
However I need for it to match up with a SQL Server table column of type bit so that it is saved as a 1 or 0.
SQL Server column:
StormOut bit
C# property
public bool StormOut { get; set; }
C# SQL statement:
string querystring = "UPDATE tblSignOnOff SET StormOut = " + storm.StormOut + " WHERE id = 1902";
Otherwise currently the SQL statement in C# is
UPDATE tblSignOnOff
SET StormOut = True
WHERE id = 1902
Which results in an error:
Invalid column name 'True'.
You have missed single quotes. Change like this:
string querystring = "UPDATE tblSignOnOff SET StormOut = '" + storm.StormOut + "' WHERE id = 1902";
But an important note: You should always use parameterized queries like below. This kind of string concatenations are open for SQL Injection:
string querystring = "UPDATE tblSignOnOff SET StormOut = #StormOut WHERE id = #id";
yourCommand.Parameters.AddWithValue("#id", 1902);
yourCommand.Parameters.AddWithValue("#StormOut", storm.StormOut);
You should use parameters and avoid string concatenation
string Command = "UPDATE tblSignOnOff SET StormOut #StormOut WHERE id = #id";
using (SqlConnection mConnection = new SqlConnection(ConnectionString))
{
mConnection.Open();
using (SqlCommand myCmd = new SqlCommand(Command, mConnection))
{
myCmd.Parameters.AddWithValue("#id", 1902); // TODO set this value dynamically
myCmd.Parameters.AddWithValue("#StormOut", storm.StormOut);
int RowsAffected = myCmd.ExecuteNonQuery();
}
}
Further modifying the answer from #S.Akbari with his suggestion for parameterized queries;
SqlCommand command = new SqlCommand();
command.CommandText = "UPDATE tblSignOnOff SET StormOut = #StormOut WHERE id = #id";
command.Parameters.AddWithValue("#StormOut", storm.StormOut);
command.Parameters.AddWithValue("#id", 1902);
I have a seleect query which the return query is used in an if statement.
The query is correct, but the problem is becuase the query returns value from multiple rows it doesnt work.
I want to use the if statement to check individual values retrived by the query.
string security = "SELECT ProjectId FROM Project_List WHERE (ProfileId = (SELECT ProfileId FROM User_Profile WHERE (UserId = #UserId)))";
using (SqlConnection myConnection = new SqlConnection(connectionString))
{
myConnection.Open();
SqlCommand myCommand = new SqlCommand(security, myConnection);
myCommand.Parameters.AddWithValue("#UserId", currentUserId);
if (Request.QueryString["ProjectId"] == myCommand.ExecuteReader().ToString())
{
}
else
{
Response.Redirect("projectlist.aspx");
}
}
Instead of ExecuteScalar, which, as it's name implies returns a single value, you have to use ExecuteReader:
SqlDataReader reader = myCommand.ExecuteReader();
while (reader.Read())
{
// grab next record selected
int project_id = (int) reader[0];
// do whatever you want with it
if (Request.QueryString["ProjectId"] == project_id.ToString())
{
}
else
{
Response.Redirect("projectlist.aspx");
}
}
The while loop will traverse all records returned by the SELECT query and exit as soon as there no more records available.
If you just want to know if you have a ProjectID equals to the one passed in by the QueryString why don't you ask directly for it in the query text?
Given the text of your current sql command I suppose that a relationship exists between a Project stored in the Project_List table and a User stored in the User_Profile table expressed through the foreign key ProfileID.
If this is the case, then your query could be rewritten to
string security = #"SELECT pl.ProjectId
FROM Project_List pl
INNER JOIN User_Profile up
ON up.ProfileID = pl.ProfileID
WHERE up.UserId = #UserId
AND pl.ProjectID = #pid";
using (SqlConnection myConnection = new SqlConnection(connectionString))
using (SqlCommand myCommand = new SqlCommand(security, myConnection))
{
myConnection.Open();
myCommand.Parameters.AddWithValue("#UserId", currentUserId);
myCommand.Parameters.AddWithValue("#pid",
Convert.ToInt32(Request.QueryString["ProjectID"]));
// Now, if ExecuteScalar returns null then there are no
// Projects for that UserID
object result = myCommand.ExecuteScalar();
if(result == null)
// No projectid for the user profile
else
// You have one or more projectids for this user profile
}
Of course this assumes that you have already checked that the Request.QueryString contains the ProjectID entry.
I want to get the value to insert a table in C#,something like this:
begin
insert into bk_library(floor,section) values('foo2','bar')
returning id into :outid;
select *from bk_library where id=:outid;
end;
Unfortunately, I failed
error info: Kiss.Linq.Linq2Sql.Test.EntryPoint.TestInsertReturnId:
Oracle.DataAccess.Client.OracleException : ORA-06550: line 3, column
1: PLS-00428: an INTO clause is expected in this SELECT statement
[Test]
public void TestInsertReturnId()
{
int ret = 0;
string connstring = "Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=pdborcl)));User Id=system;Password=****;";
string sql = #"insert into bk_library(floor,section) values('foo','bar') returning id into :outid";
sql = getSqlString();
using (DbConnection conn = new OracleConnection(connstring))
{
conn.Open();
DbCommand command = conn.CreateCommand();
command.CommandType = CommandType.Text;
command.CommandText = sql;
OracleParameter lastId = new OracleParameter(":outid", OracleDbType.Int32);
lastId.Direction = ParameterDirection.Output;
command.Parameters.Add(lastId);
ret = command.ExecuteNonQuery();
// this code work fine ,now I want to get the entire record
LogManager.GetLogger<EntryPoint>().Info("The new id ={0}", lastId.Value.ToString());
conn.Close();
}
Assert.AreNotEqual(ret, 0);
}
ParameterDirection should be ReturnValue
lastId.Direction = ParameterDirection.ReturnValue;
From < http://arjudba.blogspot.ch/2008/07/pls-00428-into-clause-is-expected-in.html?m=1>
You need to write SELECT * INTO some_variable FROM bk_library instead of SELECT * FROM bk_library because I assume you want to store the data retrieved somehow. Therefore you need to declare a new variable some_variable (I assume of type string) and modify your SELECT statement as above. The data from the statement will then be stored in your new variable.
Hope this helps
I'm trying to check if a record in a table already exists.
How could I do that?
I already wrote the following code:
string dbName = "Data Source=searchindex.db";
SQLiteConnection con = new SQLiteConnection(dbName);
con.Open();
SQLiteCommand cmd = new SQLiteCommand(con);
// If this sql request return false
cmd.CommandText = "SELECT rowid FROM wordlist WHERE word='word'";
cmd.ExecuteNonQuery();
// then add record in table
cmd.CommandText = "INSERT INTO wordlist(word) VALUES ('word')";
To check if that record exists you could simplify your code
cmd.CommandText = "SELECT count(*) FROM wordlist WHERE word='word'";
int count = Convert.ToInt32(cmd.ExecuteScalar());
if(count == 0)
{
cmd.CommandText = "INSERT INTO wordlist(word) VALUES ('word')";
cmd.ExecuteNonQuery();
}
ExecuteScalar will return the first column on the first row returned by your query.
(The link is for SqlServer, but it is identical for SQLite, because the SQLiteCommand should implement the IDbCommand interface)
Another approach to use is the following
cmd.CommandText = "INSERT INTO wordlist (word)
SELECT ('word')
WHERE NOT EXISTS
(SELECT 1 FROM wordlist WHERE word = 'word');";
cmd.ExecuteNonQuery();
This is even better because you use a single query and not two (albeit the difference in a local db should be minimal)
insert into wordlist(word)
select 'foo'
where not exists ( select 1 from wordlist where word = 'foo')
If you are using sqlite-net-pcl you could write the following.
I have a base class for several tables and in it, I have a RowExists method.
The relevant source code looks as follows:
public abstract class BaseSQLiteAccess
{
protected SQLiteConnection _databaseConnection;
protected String TableName { get; set; }
//...
protected bool RowExists(int id)
{
bool exists = false;
try
{
exists = _databaseConnection.ExecuteScalar<bool>("SELECT EXISTS(SELECT 1 FROM " + TableName + " WHERE ID=?)", id);
}
catch (Exception ex)
{
//Log database error
exists = false;
}
return exists;
}
}