Below I have a piece of code that should be writing out columns from my database, however when I try to execute, it gives me an exception that says it can't read a column with no values, but its wrong because it should contain dates in the columns that I want information to come out of.
Here is the table definition:
TABLE_CATALOG TABLE_SCHEMA TABLE_NAME TABLE_TYPE
PATRICK_DEV dbo FILE_DATE_PROCESSED BASE TABLE
Here is the code:
try
{
SqlConnection connect = new SqlConnection("Server=OMADB01;Database=PATRICK_DEV;Trusted_Connection=True;");
connect.Open();
SqlCommand command = new SqlCommand("INSERT FILE_DATE_PROCESSED(UID, FILE_DATE_PROCESSED, FILE_NAME, DATE_ENTERED) SELECT newid(), '2015-12-31 19:32:45', 'myfilename.txt', getdate()", connect);
SqlDataReader reader = null;
reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader["FILE_DATE_PROCESSED"].ToString());
Console.WriteLine(reader["DATE_ENTERED"].ToString());
}
connect.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
This is what I am dealing with right now: I have a database in SQL that looks like this:
UID FILE_DATE_PROCESSED FILE_NAME DATE_ENTERED
In this database, every time I add a file, column 2 should contain the last time I entered the file, and column 4 should contain the time I am entering the file now. This is the result that I am looking for:
UID FILE_DATE_PROCESSED FILE_NAME DATE_ENTERED
random random date the file name the current date
number
If there is a different way of solving this problem than what I have posted please let me know I will very much appreciate it.
Your query executes an INSERT (IE. Adds data to your table) It doesn't retrive any record. The INSERT statement in T-SQL could use a SELECT subquery to feed the values that are requested by the columns listed after the INSERT.
So your query add a new record every time you run it, but there is no column returned from that query and using the reader indexer on a non existant column produces the mentioned error.
If you just want to read values then you should change your query to
try
{
using(SqlConnection connect = new SqlConnection(....))
using(SqlCommand command = new SqlCommand(
#"SELECT FILE_DATE_PROCESSED, DATE_ENTERED FROM FILE_DATE_PROCESSED", connect))
{
connect.Open();
using(SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine(reader["FILE_DATE_PROCESSED"].ToString());
Console.WriteLine(reader["DATE_ENTERED"].ToString());
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
I suggest also to change the column name FILE_DATE_PROCESSED or the table name because having two objects with the same name could be an endless source of confusion and an excellent error maker
You don't have a select statement. Changing to add a select statement with names might help:
#cmdText = #"DECLARE #FILE_DATE_PROCESSED DATETIME = '2015-12-31 19:32:45',
#DATE_ENTERED DATETIME =getdate()
INSERT FILE_DATE_PROCESSED(UID, FILE_DATE_PROCESSED, FILE_NAME, DATE_ENTERED)
SELECT newid(), #FILE_DATE_PROCESSED, 'myfilename.txt',#DATE_ENTERED
SELECT #FILE_DATE_PROCESSED AS FILE_DATE_PROCESSED, #DATE_ENTERED as DATE_ENTERED"
SqlCommand command = new SqlCommand(#cmdText)
Related
I am creating a WPF program where the user can create lists of products that are stored in an .sqlite database. Each product list has it's own table inside the database, who's name is chosen by the user. I need to figure out if the table already exists when I try to create them so that if they do I can ask the user to choose a different name.
I know
SELECT name FROM sqlite_master WHERE type='table' AND name='{table_name}';
is the query used to check if a table exists but how do I get this statement in boolean form using c#?
I would assume something similar to
SQLiteConnection connection = new SQLiteConnection("Data Source=filepath;Version=3");
sql = "SELECT name FROM sqlite_master WHERE type='table' AND name='{table_name}';"
SQLiteCommand command = new SQLiteCommand(sql, connection);
command.something();
But I am unsure what function of command to use to get the Boolean value of this query and how to format it.
ExecuteNonQuery() returns -1 for SELECT statements, so it would be inappropriate to use it in this case.
try using ExecuteReader(), which returns a SqliteDataReader class that contains the HasRows property, in which should be true in case of a non-empty result set.
the code:
SQLiteConnection connection = new SQLiteConnection("Data Source=filepath;Version=3");
sql = "SELECT name FROM sqlite_master WHERE type='table' AND name='{table_name}';"
SQLiteCommand command = new SQLiteCommand(sql, connection);
try
{
var result = command.ExecuteReader();
if (result.HasRows)
{
// INSERT statement here
}
}
catch (Exception e)
{
throw e;
}
I'm trying to return the InvoiceID from the database but it keeps returning -1.
I'm trying to select the invoice ID From tblInvoice to display it on a form and also use it to insert it into a second table that has a one to many relationship with tblInvoice.
try
{
conn = new SqlConnection(conString);
conn.Open();
string select = "SELECT TOP 1 FId FROM tblFaktuur ORDER BY FId DESC";
SqlCommand cmd1 = new SqlCommand(select, conn);
i = (int)cmd1.ExecuteNonQuery();
}
catch (Exception e)
{
System.Windows.Forms.MessageBox.Show("ReadInvoiceNumber()" + e.Message);
}
return i;
When Running the query SELECT TOP 1 FId FROM tblFaktuur ORDER BY FId DESC in SQL Server it returns the value of 6 which is the last Invoice ID.
Think about that code. How do you expect a method called ExecuteNonQuery to handle a Query? Change that to ExecuteScalar. This work Perfectly Thanks to #Camilo Terevinto, i will be doing research to improve my skills atleast i know what is wrong.
I am developping an asp.net application. I would like to know how to update a field of an oracle table record, and if the record is not present, inserting it.
I have a table with the following fields NAME and SURNAME.
I would like to change the SURNAME to "new_surname" of the record where the NAME equals="name". However, if none of the records in table contains a field NAME equals to name I would like to insert a new record (SURNAME=new_surname and NAME=name).
This is my code :
OracleConnection connection = new OracleConnection(connectionstring);
try
{
connection.Open();
OracleCommand command = connection.CreateCommand();
string sql = "UPDATE TABLE SET SURNAME=\'new_surname\' WHERE NAME=\'name\'";
command.CommandText = sql;
command.ExecuteNonQuery();
connection.Close();
}
catch (Exception exp)
{
}
Is there an optimal way to do the insert only if the update find zero records matching the "where" clause. I was thinking of first doing a select count of the record matching the "where" clause, and then if I found zero results I would do an insert, and if I found at least one result I would do an update. But I find this solution a little bit heavy.
Cannot test but you could try this
using(OracleConnection connection = new OracleConnection(connectionstring))
using(OracleCommand command = connection.CreateCommand())
{
connection.Open();
string sql = #"MERGE INTO TABLE t USING dual on(name='name')
WHEN NOT MATCHED THEN INSERT (name, surname) values ('name', 'new_surname')
WHEN MATCHED THEN UPDATE SET surname = 'new_surname'";
command.CommandText = sql;
command.ExecuteNonQuery();
}
you can modify the query as :
string sql = #"IF EXISTS (SELECT * FROM \'Given Table\' WHERE NAME=\'name\') THEN
BEGIN
--your update query
END
ELSE
BEGIN
-- your Insert Query
END
END IF";
In my database i have three tables. One For employs where i keep their names, ids, salary... In the second one named Project i keep id, location, name. in the third one named WorksOn i keep the id from employs and the id from project. In my Asp .Net web site in gridview i need to display the employee's name and the name of the project that he is working.
string connect =
WebConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
SqlConnection con = new SqlConnection(connect);
try
{
con.Open();
}
catch (Exception err)
{
string error = err.Message;
con.Close();
}
SqlCommand command = new SqlCommand();
command.Connection = con;
SqlDataReader reader;
command.CommandText = "SELECT * FROM WorksON ";
reader= command.ExecuteReader();
In data source in gridview if i choose to display the values from WorksOn table it shows the id from employs and the id from project but what i need is to show the names on the employs and project.
I know that i need to do something with dataset but i don't know who.
Your SQL command must JOIN the related tables. Something like:
SELECT * FROM WorksOn JOIN Employee on WorksOn.EmployeeId = Employee.Id
Note that you should not SELECT "*" (all columns). You should only SELECT those columns that are necessary to your data view for performance.
On your SQL command, you don't mention anything about Employs. You need to use a JOIN SQL command in order to get both the employee name and the company name.
And instead of using "SELECT * FROM...", consider using the columns name instead, because you're not trying to get all the columns display. And it will help us understand the name of the columns to further help you.
Use a JOIN query like this:
SELECT project.projectName, employee.Name
FROM (worksOn
INNER JOIN employee
ON (worksOn.employeeId = employee.employeeId))
INNER JOIN project
ON (project.projectId = employee.employeeId)
AND (worksOn.projectId = project.projectId)
How to check if my table is empty from C#?
I have something like:
public MySqlConnection con;
public MySqlCommand cmd;
con = new MySqlConnection(GetConnectionString());
con.Open();
cmd = new MySqlCommand("SELECT * FROM data;", con);
Or I don't need to call SELECT statement?
You can use COUNT(*) with no WHERE close and see if exactly how many rows exist with the result.
Or you can do a SELECT (id) FROM tablename with no WHERE clause and if no rows are returned then the table is empty.
I'll give you an example in C# good luck
public bool checkEmptyTable(){
try
{
MySql.Data.MySqlClient.MySqlCommand com = new MySql.Data.MySqlClient.MySqlCommand();
conn = new MySql.Data.MySqlClient.MySqlConnection("YOUR CONNECTION");
com.Connection = conn;
com.CommandText = "SELECT COUNT(*) from data";
int result = int.Parse(com.ExecuteScalar().ToString());
return result == 0; // if result equals zero, then the table is empty
}
finally
{
conn.Close();
}
}
If 'data' might be a big table you would be better with this (where pkdata is your primary key field)
SELECT COUNT(*) FROM data WHERE pkdata = (SELECT pkdata FROM data LIMIT 1);
This will run very quickly whether you have 0 rows in 'data' or millions of rows. Using SELECT with no WHERE or ORDER BY means it just pulls the first row available, LIMIT 1 stops it getting more than 1.
Maybe something to look for if you have a program that ran very quickly six months ago but now runs like a dog in treacle!
SELECT COUNT(*)
FROM table
WHERE `col_name` IS NOT NULL