I am semi-new to C# but in particular using Sqlite within C#, currently I have a SQlite DB setup fine in terms of it connects with the application well I am running windows form application and I have bound a table within the database to a datagrid view.
This is all fine I have a function setup to run queries where i pass the SQL statement as a string to the function and it runs it as a query.
I was wandering how I do I get a result back from the query I know obviosuly it will be somthing like
private string QueryResult(string query){
connect
run query
read query
return result
}
All th examples I have seen use Sqlreader but I can't seem to get it work, I am really used to using PHP with SQL and that seems so much simpler than using it in C# can someone explain or point out somewhere I might be able to find a tutuorial or function that you can run any query in by passing it as a string and getting the result returned pretty simply? The results I need wont be arrays or huge things I am only looking to return 1 word strings or numbers at a time so I don't need anything complicated.
Please help me out I spent about 4 hours reading about this stuff last night and didn't seem to get anywhere.
Try this, maybe it will help you:
public string QueryResult(string query)
{
string result = "";
SQLiteConnection sqlite = new SQLiteConnection("Data Source=/path/to/file.db");
try
{
sqlite.Open(); //Initiate connection to the db
SQLiteCommand cmd = sqlite.CreateCommand();
cmd.CommandText = query; //set the passed query
result = cmd.ExecuteScalar().ToString();
}
finally
{
sqlite.Close();
}
return result;
}
Heres a method that I have Used....
First off, build a class to represent a Table in your DataBase :-
public class Contact
{
public int ContactID { get; set; }
public string Surname { get; set; }
public string Forename { get; set; }
public string MobileNumber { get; set; }
public string EmailAddress { get; set; }
public string Information { get; set; }
}
Then I load this Data into an IEnumerable List :-
public List<Contact> GetContacts()
{
DataTable dt = new DataTable();
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [Contacts]", Connection);
Adapter.SelectCommand = cmd;
Connection.Open();
Adapter.SelectCommand.ExecuteNonQuery();
Adapter.Fill(dt);
Connection.Close();
var Contacts = (from row in dt.AsEnumerable()
select new Contact
{
ContactID = row.Field<int>("ContactID"),
Surname = row.Field<string>("Surname"),
Forename = row.Field<string>("Forename"),
MobileNumber = row.Field<string>("MobileNumber"),
EmailAddress = row.Field<string>("EmailAddress"),
Information = row.Field<string>("Information")
}).ToList();
return Contacts;
}
In My application I create an Instance of this Object :-
public List<Contact> contactData;
contactData = dc.GetContacts();
I now have the power to manipulate the data using LINQ :-
var Query = ConactData.Where(item=> item.ContactID == 10)
.Select(item=> item.Surname).toString();
You can use LINQ to query your Data and store it as Lists, Strings etc etc.
Hope This Helps.
Usually, I do something like:
string CONNECTION_STRING = "Persist Security Info=False; Integrated Security = SSPI; Initial Catalog=DATABASENAME;Data Source=SERVERIP";
string query = "IF OBJECT_ID('TABLE_NAME') IS NOT NULL SELECT * FROM TABLE_NAME";
using (SqlConnection Connection = new SqlConnection(CONNECTION_STRING))
{
using (SqlCommand sqlCommand = new SqlCommand(query, ConnectionString))
{
try
{
Connection.Open();
SqlDataReader queryCommandReader = sqlCommand.ExecuteReader();
DataTable dataTable = new DataTable();
dataTable.Load(queryCommandReader);
if (dataTable != null)
{
if (dataTable.Rows != null)
{
if (dataTable.Rows.Count > 0)
{
String rowText = "";
rowText += dataTable.Rows[ROW_NUM] [COLUMN_NAME];
}
}
}
}
catch (Exception)
{
...
}
finally
{
...
}
//in normal logic
SELECT (SELECT SUM(column_name) FROM table_name WHERE condition) - (SELECT SUM(column_name) FROM table_name WHERE condition)
//actual coding example
public void total_due()
{
string query = "select (select sum(amount) from table_name where id>0 and amount>paid and [order no] like '" + textbox1.Text + "%' and [name] like '" + textbox2.Text + "%' and [date] like '" + textbox3.Text + "%' ) - (select sum(paid) from table_name where id>0 and amount>paid and [order no] like '" + textbox1.Text + "%' and [name] like '" + textbox2.Text + "%' and [date] like '" + textbox3.Text + "%' )";
SqlConnection con = new SqlConnection("server=server_name;Database=database_name;UID=sa;Password=password;");
con.Open();
SqlCommand cmd = new SqlCommand(query,con);
due.Text = cmd.ExecuteScalar().ToString();
con.Close();
}
Related
I want to retrive data from two differentables in my mysql data base so i created one connection and two readers, The second reader is not returning any results but the first reader is.
public List<BlogContentItemClass> BCITLIST = new List<BlogContentItemClass>();
// GET: api/BlogContents
[HttpGet]
public List<BlogContentItemClass> Get(string id)
{
string sqlstring = "server=; port= ; user id =;Password=;Database=;";
MySqlConnection conn = new MySqlConnection(sqlstring);
try
{
conn.Open();
}
catch (MySqlException ex)
{
throw ex;
}
string Query = "SELECT * FROM test.blogtable where `id` = '" + id + "' ";
MySqlCommand cmd = new MySqlCommand(Query, conn);
MySqlDataReader MSQLRD = cmd.ExecuteReader();
BlogContentItemClass BCIT = new BlogContentItemClass();
Label BLOGID = new Label();
if (MSQLRD.HasRows)
{
while (MSQLRD.Read())
{
string TC = (MSQLRD["Topic"].ToString());
string CT = (MSQLRD["Category"].ToString());
string SM = (MSQLRD["Summary"].ToString());
string BID = (MSQLRD["id"].ToString());
BCIT.TopicSaved1 = TC;
BCIT.CategoriesSaved1 = CT;
BCIT.SummarySaved1 = SM;
BLOGID.Text = BID;
BCIT.TotalBodyStackLayout1.Add("Hello");
}
}
BCITLIST.Add(BCIT);
MSQLRD.Close();
string Query1 = "SELECT * FROM test.blogbodytable where `BlogID` = '" + BLOGID.Text + "' ";
MySqlCommand cmd1 = new MySqlCommand(Query1, conn);
MySqlDataReader MSQLRD1 = cmd1.ExecuteReader();
if (MSQLRD1.HasRows)
{
while (MSQLRD1.Read())
{
string BLOGBODY ;
BLOGBODY = (MSQLRD1["BlogBody"].ToString());
BCIT.TotalBodyStackLayout1.Add(BLOGBODY);
}
}
BCITLIST.Add(BCIT);
conn.Close();
return BCITLIST;
}
from my code the line BCIT.TotalBodyStackLayout1.Add("Hello"); in the first reader does add "hello" to the BCIT.TotalBodyStacklayout1, but the line BCIT.TotalBodyStackLayout1.Add( BLOGBODY); does not work, what am i doing wrong?
Can you be more specific what you mean by 'BCIT.TotalBodyStackLayout1.Add(BLOGBODY);' does not work. Are you getting any exception? or if BLOGBODY coming empty? There are few primitive troubleshooting steps you can perform to nail-down the issue
confirm what BLOGID.Text you are getting from your previous query and corresponding data is available in test.blogbodytable for that id.
if (MSQLRD1.HasRows) is resolving to true
Were you able to get inside while (MSQLRD1.Read())
Is there anything wrong with my code? It is not showing data in textboxes. The same funtion is working for another table in database but not for this one.
private void metroButton1_Click(object sender, EventArgs e)
{
con = new SqlConnection(constr);
String query = "Select FROM Student WHERE Std_ID = '" + metroTextBox1.Text + "'";
cmd = new SqlCommand(query, con);
con.Open();
try
{
using (SqlDataReader read = cmd.ExecuteReader())
{
while (read.Read())
{
// metroTextBox1.Text = (read["ID"].ToString());
metroTextBox2.Text = (read["Name"].ToString());
metroTextBox3.Text = (read["F_Name"].ToString());
metroTextBox4.Text = (read["Std_Age"].ToString());
metroTextBox5.Text = (read["Address"].ToString());
metroTextBox6.Text = (read["Program"].ToString());
metroComboBox1.Text = (read["Course"].ToString());
}
}
}
finally
{
con.Close();
}
}
you need to give column names in the select statement or select *
for example :
String query = "Select * from Student WHERE Std_ID = '" + metroTextBox1.Text + "'";
Not related to Question: you can change the while loop to if condition if you have one record for given id. even there are many records for given id you will see the last record data only because of the while loop will overwrite the textboxes in every record.
Update :
There isn't anything wrong with Syntax because the same syntax is
working for modifying teacher funtion.
No, this is incorrect, remove the try catch in your code then you will see the exception of syntax error
Hello guys I am trying to do some stuff while reading. What I am trying to do is edit row which was just read. But I get error. Maybe u have some suggestions how should I fix it, to make it work without quitting the data reader. P.S: Ignore that, that queries are open for SQL injections .
string select = "Select * FROM ivykiai WHERE `Ivikio diena` MOD Periodiskumas_d = 0 AND `Ivikio diena` > 0 AND `Ivikio diena` < `Dif dien`";
MySqlCommand command = new MySqlCommand(select, cnn);
MySqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
db1 = (now - Convert.ToDateTime(reader["Nuo"])).TotalDays;
MessageBox.Show(db1.ToString());
db1 = db1 - Convert.ToInt32(reader["Ivikio diena"]);
MessageBox.Show(db1.ToString());
b = Convert.ToInt32(db1) / Convert.ToInt32(reader["Periodiskumas_d"]);
MessageBox.Show(b.ToString());
a =+ Convert.ToInt32(reader["Suma"]);
MessageBox.Show(a.ToString());
a = a * b;
MessageBox.Show(a.ToString());
string prideti = "Update Lesos Set Grynieji=Grynieji + '"+ a +"'";
MySqlCommand prideti_cmd = new MySqlCommand(prideti, cnn);
string p = prideti_cmd.ExecuteNonQuery().ToString();
string update = "UPDATE Ivikiai Set `Ivykio diena`+= '" + db1 + "'";
MySqlCommand update_cmd = new MySqlCommand(update, cnn);
string u = update_cmd.ExecuteNonQuery().ToString();
}
reader.Close();
cnn.Close();
You can't execute prideti_cmd and update_cmd using the same connection inside the while (reader.Read()) block and reader is still open, however you can do that outside the while (reader.Read()) block and after closing reader. I would suggest creating the following class
public class MyClass
{
public DateTime Nuo { get; set; }
public int IvikioDiena { get; set; }
public int Periodiskumas_d { get; set; }
public int Suma { get; set; }
}
and change your code as below
string select = "Select * FROM ivykiai WHERE `Ivikio diena` MOD Periodiskumas_d = 0 AND `Ivikio diena` > 0 AND `Ivikio diena` < `Dif dien`";
using (MySqlCommand command = new MySqlCommand(select, cnn))
{
// execute the select query and store the results to list variable
List<MyClass> list = new List<MyClass>();
using (MySqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
MyClass record = new MyClass();
record.Nuo = Convert.ToDateTime(reader["Nuo"]);
record.IvikioDiena = Convert.ToInt32(reader["Ivikio diena"]);
record.Periodiskumas_d = Convert.ToInt32(reader["Periodiskumas_d"]);
record.Suma = Convert.ToInt32(reader["Suma"]);
list.Add(record);
}
}
// enumerate list and execute both the update queries
foreach (var record in list)
{
db1 = (now - record.Nuo).TotalDays;
MessageBox.Show(db1.ToString());
db1 = db1 - record.IvikioDiena;
MessageBox.Show(db1.ToString());
b = Convert.ToInt32(db1) / record.Periodiskumas_d;
MessageBox.Show(b.ToString());
a =+ record.Suma;
MessageBox.Show(a.ToString());
a = a * b;
MessageBox.Show(a.ToString());
string prideti = "Update Lesos Set Grynieji=Grynieji + '"+ a +"'";
MySqlCommand prideti_cmd = new MySqlCommand(prideti, cnn);
string p = prideti_cmd.ExecuteNonQuery().ToString();
string update = "UPDATE Ivikiai Set `Ivykio diena`+= '" + db1 + "'";
MySqlCommand update_cmd = new MySqlCommand(update, cnn);
string u = update_cmd.ExecuteNonQuery().ToString();
}
}
Generally you can ever only have one active command - SQL Server MARS being a little exceptiohn.
So, you can not use a connection WHILE IT HAS AN OPEN READER. Your first need to finish reading, then can update- or use anothe connection, which will get you into transaction isolation troubles.
Try this:
using (MySqlConnection cnn = new MySqlConnection(dbConnectionString))
{
cnn.Open();
MySqlCommand command = new MySqlCommand(select, cnn);
using (MySqlDataReader reader = command.ExecuteReader())
{
db1 = (now - Convert.ToDateTime(reader["Nuo"])).TotalDays;
MessageBox.Show(db1.ToString());
db1 = db1 - Convert.ToInt32(reader["Ivikio diena"]);
MessageBox.Show(db1.ToString());
b = Convert.ToInt32(db1) / Convert.ToInt32(reader["Periodiskumas_d"]);
MessageBox.Show(b.ToString());
a = +Convert.ToInt32(reader["Suma"]);
MessageBox.Show(a.ToString());
a = a * b;
MessageBox.Show(a.ToString());
}
string prideti = "Update Lesos Set Grynieji=Grynieji + '" + a + "'";
MySqlCommand prideti_cmd = new MySqlCommand(prideti, cnn);
string p = prideti_cmd.ExecuteNonQuery().ToString();
string update = "UPDATE Ivikiai Set `Ivykio diena`+= '" + db1 + "'";
MySqlCommand update_cmd = new MySqlCommand(update, cnn);
string u = update_cmd.ExecuteNonQuery().ToString();
}
All of the variables needed for the ExecuteNonQuery() are set when the data is read so you can use them outside the MySqlDataReader.ExecuteReader() function.
My table structure is as follows:
Session
--------------
SessionID (PK)
RoomID
SessionDate
SessionTimeStart
SessionTimeEnd
I have a following query which will always return one row and display in DGV. I use DataAdapter for connection:
DataTable queryResult = new DataTable();
string ConnStr = "Data Source=DUZY;Initial Catalog=AutoRegSQL;Integrated Security=True";
SqlConnection MyConn = new SqlConnection(ConnStr);
MyConn.Open();
//SQL query that returns todays sessions for the given roomID
string query = #"SELECT SessionID, RoomID, SessionDate, SessionTimeStart, SessionTimeEnd" +
" FROM [Session] " +
" WHERE RoomID = #RoomID " +
" AND SessionDate = cast(getdate() as date) ";
SqlCommand command = new SqlCommand(query, MyConn);
command.Parameters.Add("RoomID", SqlDbType.Char).Value = RoomID;
SqlDataAdapter adapter = new SqlDataAdapter(command);
adapter.Fill(queryResult);
I would like to save the query result into multiple strings representing table columns, i.e.
SessionIDstring = query result for SessionID column
RoomIDstring = query result for RoomID column
and so on...
Is it possible to achieve it using one query, or do I have to create 5 queries for each column?
Something similar to this, perhaps, using ADO.NET?
//SQL query that returns todays sessions for the given roomID
string query = #"SELECT SessionID, RoomID, SessionDate, SessionTimeStart, SessionTimeEnd" +
" FROM [Session] " +
" WHERE RoomID = #RoomID " +
" AND SessionDate = cast(getdate() as date) ";
using (var connection = new SqlConnection(ConnStr))
using (var command = new SqlCommand(query, connection))
{
command.Parameters.Add("RoomID", SqlDbType.Char).Value = RoomID;
try
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.Read())
{
// Note that reader[x] has the equivalent type to the type
// of the returned column, converted using
// http://msdn.microsoft.com/en-us/library/cc716729.aspx
// .ToString() if the item isn't null is always ok
string SessionIDstring = reader[0].ToString(); // it should be an int
// reading it twice is ok
int RoomID = (int)reader[1]; // it should be an int
string RoomIDstring = reader[1].ToString(); // it should be an int
if (reader.Read())
{
throw new Exception("Too many rows");
}
}
else
{
throw new Exception("No rows");
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
This code was adapted from MSDN ADO.NET Code Examples. I added some usings and made it single row. I don't even want to know why MSDN examples don't go the full length with using.
Note that SqlDataAdapter are built to recover multiple rows/big data and put them in a DataSet. You can use them for single row data, but it's much easier to simply use a SqlDataReader if you only want to fill some variables.
declare #col1 int
declare #col2 varchar(42)
select #col1 = col1
, #col2 = col2
, ....
You could create a class like so...
public class SessionDto
{
public string SessionID {get; set;}
public string RoomID {get; set;}
public string SessionDate {get; set;}
public string SessionTimeStart {get; set;}
public string SessionTimeEnd {get; set;}
}
And then have a method that takes a Room ID and builds your session object
public SessionDto GetSessionData(int roomId)
{
using (var cnn = new SqlConnection(ConnStr))
{
SessionDto sessionDto;
string query = #"SELECT SessionID, RoomID, SessionDate, SessionTimeStart, SessionTimeEnd" +
" FROM [Session] " +
" WHERE RoomID = #RoomID " +
" AND SessionDate = cast(getdate() as date) ";
cnn.Open();
using (var cmd = new SqlCommand(query,cnn))
{
cmd.Parameters.Add("#RoomID", SqlDbType.Char).Value = roomId;
using (var rdr = cmd.ExecuteReader())
{
if (rdr.HasRows)
{
while (rdr.Read())
{
sessionDto = new sessionDto{
SessionID = rdr.GetString(0),
RoomID = rdr.GetString(1),
SessionDate = rdr.GetString(2),
SessionTimeStart = rdr.GetString(3),
SessionTimeEnd = rdr.GetString(4)
};
}
}
}
}
}
return sessionDto;
}
A lot of this is hand typed as I havent got access to VS right now,
but you should get it to work.
Also, I have used rdr.GetString(), there are other methods for GetType().
At the moment i have a textbox and a button and i can read the textbox fine and it searches the databse for say "apple"
but if there is a result called "red apple" it will not return it.
I have tried
string getTheBox = (this.searchBox.Text);
string request = "%" + getTheBox + "%";
But it doesn't seem to be working. This is with "request" being the string variable.
EDIT to include the SQL request part
SqlDataSource2.SelectCommand = "SELECT Recipe_Name FROM New_Recipe WHERE [ingredient1]=#request
SqlDataSource2.SelectParameters.Add(newParameter("request",System.TypeCode.String));
SqlDataSource2.SelectParameters["request"].DefaultValue = request;
The adding of % is correct, but you need to change your sql query
you need to use the LIKE operator
for example THE QUERY could be
"SELECT Recipe_Name FROM New_Recipe WHERE ingredient1 LIKE #request"
and your code
string request = "%" + getTheBox + "%";
string sqlText = "SELECT Recipe_Name FROM New_Recipe WHERE ingredient1 LIKE #request";
using(SqlConnection cn = GetSqlConnection())
{
cn.Open();
using(SqlCommand cmd = new SqlCommand(sqlText, cm);
{
cmd.Parameters.AddWithValue("#request", request);
SqlDataReader dr = cmd.ExecuteReader();
while(dr.Read())
{
......
}
}
}
Please post your SQL query too. Perhaps you need to change WHERE FruitName = #FruitName to WHERE FruitName LIKE #FruitName
This is a horrible idea, as anyone can run sql injection. You probably want something akin to
Sqlcommand.Prepare
As it will let you set safer arguements. And have two words.
I usually have a few helper functions to add like to my queries depending on what I need done.
public List<T> GetRecipesThatContain<T>(string ingredient)
{
const string commandText = "SELECT Recipe_Name FROM New_Recipe WHERE ingredient1 LIKE #SearchTerm";
var searchTerm = Contains(ingredient);
using(var connection = GetSqlConnection())
{
connection.Open();
using(var command = new SqlCommand(commandText, connection);
{
command.Parameters.AddWithValue("#SearchTerm", searchTerm);
using(var reader = command.ExecuteReader())
{
var results = new List<T>();
while(reader.Read())
{
// Get results
// results.Add(result);
}
return results;
}
}
}
}
private string StartsWith(string searchTerm)
{
return string.Format("{0}%", searchTerm);
}
private string EndsWith(string searchTerm)
{
return string.Format("%{0}", searchTerm);
}
private string Contains(string searchTerm)
{
return string.Format("%{0}%", searchTerm);
}