Connect to SQLite using C# - c#

I got the following error:
Input string was not in a correct format
Can anyone help to me? Here is my input parameters and method:
public void insertSQL(Dictionary<string,object> objects, string dbConnectionString)
{
openConnection(dbConnectionString);
SQLiteCommand command = new SQLiteCommand(sqliteCon);
command.CommandText = "INSERT INTO AppUser VALUES(#name, #surname)", objects, "Data Source=sample.s3db"
command.CommandType = CommandType.Text;
foreach (var param in objects)
{
command.Parameters.Add(new SQLiteParameter(param.Key,SqlDbType.NVarChar){ Value = (String)param.Value} );
Console.WriteLine(command.Parameters.Count);
}
command.ExecuteNonQuery();
closeConnection();
}

You must tell for which columns you are presenting values (other will get their default values)
Something like :
INSERT INTO AppUser (name,surname) VALUES(#name, #surname) ...

Parameters' name in query should be equal to parameters you assign values to:
using (SQLiteConnection connection = new SQLiteConnection(connectionString))
using (SQLiteCommand command = new SQLiteCommand(connection))
{
command.CommandText = "...";
command.Parameters.Add("#name", SqlDbType.NVarChar).Value = name;
command.Parameters.Add("#surname", SqlDbType.NVarChar).Value = value;
connection.Open();
command.ExecuteNonQuery();
}

Related

c# database Select then insert. But the value is 0

I am trying to select then insert a datetime from Table 1 to Table 2. I have successfully insert the data. However, the datetime shown in Table 2 is 0000-00-00 00:00:00. Idk where is the error. Someone please help me with this problem. I am struggling with this. And is this the correct way to SELECT then insert ? (Select from Table 1 then INSERT into Table 2)
try
{
string myConnectionString;
myConnectionString= "server=localhost;uid=root;pwd=root;database=medicloud;SslMode=None;charset=utf8";
MySqlConnection connection = new MySqlConnection(myConnectionString);
MySqlCommand cmd = new MySqlCommand();
cmd.CommandType = CommandType.Text;
EncodingProvider ppp;
ppp = CodePagesEncodingProvider.Instance;
Encoding.RegisterProvider(ppp);
connection.Open();
string select = "Select time from assign where userId=#name";
cmd.Parameters.AddWithValue("#name", txtValue.Text);
cmd.CommandText = select;
cmd.Connection = connection;
MySqlDataReader selectAssign = cmd.ExecuteReader();
selectAssign.Read();
string assign = (selectAssign["time"].ToString());
selectAssign.Close();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT into bluetooth (userId,arm,armNumberDone,armNumber,comDate,assignDate,status) VALUES (#name, #stupid0, #stupid1, #stupid2, #stupid3, #stupid4, #stupid5)";
cmd.Parameters.AddWithValue("#stupid0", databaseLine);
cmd.Parameters.AddWithValue("#stupid1", counter);
cmd.Parameters.AddWithValue("#stupid2", databaseValue);
cmd.Parameters.AddWithValue("#stupid3", DateTime.Now);
cmd.Parameters.AddWithValue("#stupid4", assign);
cmd.Parameters.AddWithValue("#stupid5", complete);
cmd.Connection = connection;
cmd.ExecuteNonQuery();
connection.Close();
}
catch (MySqlException ex)
{
txtExercise.Text = ex.ToString();
}
Please try with this
try
{
string myConnectionString;
myConnectionString = "server=localhost;uid=root;pwd=root;database=medicloud;SslMode=None;charset=utf8";
MySqlConnection connection = new
MySqlConnection(myConnectionString);
MySqlCommand cmd = new MySqlCommand();
cmd.CommandType = CommandType.Text;
EncodingProvider ppp;
ppp = CodePagesEncodingProvider.Instance;
Encoding.RegisterProvider(ppp);
connection.Open();
string select = "Select time from assign where userId=#name";
cmd.Parameters.AddWithValue("#name", txtValue.Text);
cmd.CommandText = select;
cmd.Connection = connection;
MySqlDataReader selectAssign = cmd.ExecuteReader();
selectAssign.Read();
string assign = (selectAssign["time"].ToString());
selectAssign.Close();
DateTime assignDate = DateTime.Now;
DateTime.TryParseExact(assign, out assignDate);
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT into bluetooth
(userId,arm,armNumberDone,armNumber,comDate,assignDate,status) VALUES (#name,
#stupid0, #stupid1, #stupid2, #stupid3, #stupid4, #stupid5)";
cmd.Parameters.AddWithValue("#stupid0", databaseLine);
cmd.Parameters.AddWithValue("#stupid1", counter);
cmd.Parameters.AddWithValue("#stupid2", databaseValue);
cmd.Parameters.AddWithValue("#stupid3", DateTime.Now);
cmd.Parameters.AddWithValue("#stupid4", assignDate);
cmd.Parameters.AddWithValue("#stupid5", complete);
cmd.Connection = connection;
cmd.ExecuteNonQuery();
connection.Close();
}
catch (MySqlException ex)
{
txtExercise.Text = ex.ToString();
}
}
cmd.Parameters.AddWithValue("#stupid3", DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"));
cmd.Parameters.AddWithValue("#stupid4", GetDateString(assign));
Have a method like this:
public static string GetDateString(string date)
{
DateTime theDate;
if (DateTime.TryParseExact(date, "dd/MM/yyyy HH:mm:ss",
CultureInfo.InvariantCulture, DateTimeStyles.None, out theDate))
{
// the string was successfully parsed into theDate
return theDate.ToString("dd/MM/yyyy HH:mm:ss");
}
else
{
// the parsing failed, return some sensible default value
return string.Empty;
}
}
You need to use .ExecuteReader() the use .Read() to move to each row in the result set. If you are sure the exactly one row will be returned, use .ExecuteScalar() instead. Research on the difference of both online. Below is an example using .ExecuteReader().
I also re-wrote to use using statements to simplify a bit but not deviate too much from your original code so you do not need to worry about closing and disposing resources since they inherit from IDisposable and will do that automatically once they exit the using block:
string assign = DateTime.Now.ToString();
string myConnectionString;
myConnectionString= "server=localhost;uid=root;pwd=root;database=medicloud;SslMode=None;charset=utf8";
string select = "Select time from assign where userId=#name";
using (MySqlConnection con = new MySqlConnection(myConnectionString))
{
using (MySqlCommand cmd = new MySqlCommand(select))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
cmd.Parameters.AddWithValue("#name", txtValue.Text);
using (MySqlDataReader cursor = cmd.ExecuteReader())
{
while (cursor.Read())
{
assign = cursor["time"];
}
}
}
string insert = "INSERT into bluetooth (userId,arm,armNumberDone,armNumber,comDate,assignDate,status) VALUES (#name, #stupid0, #stupid1, #stupid2, #stupid3, #stupid4, #stupid5)";
using (MySqlCommand cmd = new MySqlCommand(insert))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
cmd.Parameters.AddWithValue("#stupid0", databaseLine);
cmd.Parameters.AddWithValue("#stupid1", counter);
cmd.Parameters.AddWithValue("#stupid2", databaseValue);
cmd.Parameters.AddWithValue("#stupid3", DateTime.Now);
cmd.Parameters.AddWithValue("#stupid4", assign);
cmd.Parameters.AddWithValue("#stupid5", complete);
cmd.ExecuteNonQuery();
}
}

Getting a query result into a Variable then passing it to a command

Here is my code. I am trying to get a result of a SQL query stored in query1 variable, and want to use that result in a SQL query stored in query variable. Messagebox is irrelevant, I just wrote it to see if I am getting the correct results from listbox1 or not.If i hardcode the query1's result into command parameters, it works perfectly.
private void btnAddCoarse_click(object sender, EventArgs e)
{
MessageBox.Show(listBox1.SelectedItem.ToString());
string query1 ="SELECT ogrenciNo FROM ders,ogrenci,Enrollment WHERE ogrenciId=ogrenciNo AND dersId=dersKodu AND ogrenci.email='" + mainform.Username + "' AND Enrollment.dersId='"+listBox1.SelectedValue+"'";
string query = "INSERT INTO Enrollment(dersId,ogrenciId) VALUES (#dersId, #ogrenciId)";
using (connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(query, connection))
{
connection.Open();
command.Parameters.AddWithValue("#dersId", listBox1.SelectedValue);
command.Parameters.AddWithValue("#ogrenciId",//this is where i need the query1//);
command.ExecuteNonQuery();
PopulateList2();
}
}
You only need one sql command. The structure would be like this:
insert into table2
(field1, field2)
select value1, value2
etc
int id;
using (connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(query1, connection))
{
connection.Open();
id = Convert.ToInt32(command.ExecuteScalar()); //I guess it returns only 1 id?..
}
Try doing this
private void btnAddCoarse_click(object sender, EventArgs e)
{
//MessageBox.Show(listBox1.SelectedItem.ToString());
string query1 ="SELECT ogrenciNo FROM ders,ogrenci,Enrollment WHERE ogrenciId=ogrenciNo AND dersId=dersKodu AND ogrenci.email='" + mainform.Username + "' AND Enrollment.dersId='"+listBox1.SelectedValue+"'";
string query = "INSERT INTO Enrollment(dersId,ogrenciId) VALUES (#dersId, #ogrenciId)";
using (connection = new SqlConnection(connectionString))
{
int result=0;
using (SqlCommand command = new SqlCommand(query1, connection))
{
connection.Open();
result=Convert.ToInt32(command.ExecuteScalar());
connection.Close();
}
using (SqlCommand command = new SqlCommand(query, connection))
{
connection.Open();
command.Parameters.AddWithValue("#dersId", listBox1.SelectedValue);
command.Parameters.AddWithValue("#ogrenciId",result);
command.ExecuteNonQuery();
PopulateList2();
}
}
}

SQL Server within & using stored procedure

Trying to create a asp.net c# form for learning purposes at home and i'm absolutely struggling to connect to my storedprocedure.
I'm definitely in the right database as when I start the database by cmdprompt and connect to it via datasource in visual design it connects and finds the stored procedure. So there must be something I am doing wrong? I've been searching Google for about 30-40 minutes now and everything I've tried hasn't resolved my issue. Any suggestions please?
const string constring = #"Data Source=(localdb)\ProjectsV12;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False";
public static int InsertEnquiry(string Name, string Subject, string Email, string Message, string Phone) {
//default ticketid of 0 which will be changed to -1 if an error or greater than 0 if successful
int TicketID = 0;
if (String.IsNullOrEmpty(Phone)) Phone = "0";
using (var conn = new SqlConnection(constring)) {
//create command
SqlCommand command = new SqlCommand();
//tell the command which connection its using
command.Connection = conn;
//inform command that it is a stored procedure and the name of stored procedure
command.CommandText = "InsertEnquiry";
command.CommandType = CommandType.StoredProcedure;
//add the parameters to the sqlcommand
command.Parameters.Add(new SqlParameter("#Name", SqlDbType.NVarChar)).Value = Name;
command.Parameters.Add(new SqlParameter("#Subject", SqlDbType.NVarChar)).Value = Subject;
command.Parameters.Add(new SqlParameter("#Phone", SqlDbType.NVarChar)).Value = Phone;
command.Parameters.Add(new SqlParameter("#Email", SqlDbType.NVarChar)).Value = Email;
command.Parameters.Add(new SqlParameter("#Message", SqlDbType.NVarChar)).Value = Message;
// try run command and set TicketID to the row inserted into the table.
try {
conn.Open();
//run command
command.ExecuteNonQuery();
//return scope identity of row.
TicketID = (int)command.Parameters["#TicketID"].Value;
}
catch (Exception e) {
//show -1 to state there is an error
TicketID = -1;
}
}
return TicketID;
}
}
1st
I think you are connected to the wrong db, probably you are in master.
Run this piece of code and check the name of the database and see if it's the one that you want.
public static string checkDB()
{
string dbName = "";
using (var conn = new SqlConnection(constring))
{
//create command
SqlCommand command = new SqlCommand();
//tell the command which connection its using
command.Connection = conn;
//inform command that it is a stored procedure and the name of stored procedure
command.CommandText = "select DB_NAME()";
command.CommandType = CommandType.Text;
// try run command and set TicketID to the row inserted into the table.
try
{
conn.Open();
//run command
SqlDataReader reader = command.ExecuteReader();
reader.Read();
dbName = reader[0].ToString();
}
catch (Exception e)
{
}
}
return dbName;
}
2nd
You are trying to get the value from the parameter #TicketID but you didn't specify this parameter as an output parameter.
command.Parameters.Add("#TicketID", SqlDbType.Int).Direction = ParameterDirection.Output;
EDIT1:
This is how do you put the db name in the connection string:
const string constring = #"Data Source=(localdb)\ProjectsV12;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;Initial Catalog=MY_DB_NAME";

How to apply National Character set to dynamic query

I am trying to apply N before variable name for Unicode as mentioned in How to use 'LIKE' statement with unicode strings?
With the following code I am getting following error. What need to be corrected here?
Exception: Invalid column name 'N#input'.
string commandText = #"SELECT AccountType,*
FROM Account
WHERE AccountType LIKE N#input ";
CODE
static void Main(string[] args)
{
string result = DisplayTest("Daily Tax Updates: ----------------- Transactions");
}
private static string DisplayTest(string searchValue)
{
string test = String.Empty;
string connectionString = "Data Source=.;Initial Catalog=LibraryReservationSystem;Integrated Security=True;Connect Timeout=30";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string commandText = #"SELECT AccountType,*
FROM Account
WHERE AccountType LIKE N#input ";
using (SqlCommand command = new SqlCommand(commandText, connection))
{
command.CommandType = System.Data.CommandType.Text;
command.Parameters.AddWithValue("#input", "%" + searchValue + "%");
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
test = reader.GetString(0);
}
}
}
}
}
return test;
}
I see a few issues.
string commandText = #"SELECT AccountType,*
FROM Account
WHERE AccountType LIKE N#input";
should be
string commandText = #"SELECT AccountType,*
FROM Account
WHERE AccountType LIKE #input";
...
command.Parameters.Add("#input",System.Data.SqlDbType.NVarChar,<<size>>);
command.Parameters[0].Value = "%" + searchValue + "%";
I see you're trying to use a nvarchar parameter. I think .net does that by default with .AddWithValue
I'm not sure why do you need the typecast to nvarchar, you should be fine without the 'N' part.
That part you need when you want to specify that a string literal should be treated as nvarchar not as varchar, as in SELECT * from Table where field like N'%VALUE%'
Otherwise, you just declare your variable/parameter as nvarchar
Taken from this stack Stack overflow
SqlParameter parameter = new SqlParameter();
parameter.ParameterName = "#CategoryName";
parameter.SqlDbType = SqlDbType.NVarChar;
parameter.Direction = ParameterDirection.Input;
parameter.Value = categoryName;
Try this one -
private static string DisplayTest(string searchValue)
{
string connectionString = "Data Source=.;Initial Catalog=LibraryReservationSystem;Integrated Security=True;Connect Timeout=30";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string commandText = #"SELECT AccountType,* FROM Account WHERE AccountType LIKE #input";
using (SqlCommand command = new SqlCommand(commandText, connection))
{
command.CommandType = System.Data.CommandType.Text;
command.Parameters.Add("#input", SqlDbType.NVarChar);
command.Parameters["#input"].Value = string.Format("%{0}%", searchValue);
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
return reader.GetString(0);
}
}
}
}
}
return String.Empty;
}

Getting ORA-01036 error when using output parameter in C#

I am having a problem with an Output parameter in C#/Oracle. I have isolated the code that I need to get working.
This is part of a much larger SQL statement, so do not worry too much if it doesn't make sense. In short I need to copy a row, give it a new ID and return that new ID. I tried using "RETURNING" which did not work. I see no reason why the code below should not work, but I'm getting an "ORA-01036: illegal variable name/number" error. Can anyone see what I'm doing wrong?
using (OracleConnection conn = new OracleConnection(connString))
{
// Open connection and create command.
conn.Open();
using (OracleCommand cmd = new OracleCommand())
{
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("outValue", OracleType.Int32).Direction = ParameterDirection.Output;
cmd.CommandText = "SELECT seq.nextval INTO :outValue FROM dual";
try
{
cmd.ExecuteNonQuery();
}
catch (Exception e)
{
// This is just to see the exception when it fails.
}
}
}
The name of the parameter doesn't match.
cmd.Parameters.Add(":outValue", OracleType.Int32).Direction.......;
^
I have also seen this variation on the query syntax
"BEGIN SELECT seq.nextval INTO :outValue FROM dual END;"
You are using named parameters. Try setting:
cmd.BindByName = true;
Have you tried 'returning' keyword like this?
This code works for me.
using (OracleConnection conn = new OracleConnection(connString))
{
// Open connection and create command.
conn.Open();
using (OracleCommand cmd = new OracleCommand())
{
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("outValue", OracleType.Int32).Direction = ParameterDirection.Output;
cmd.CommandText = "insert into table (id, value) values (seq.nextval, 'value') returning id into :outValue";
cmd.ExecuteNonQuery();
}
}

Categories