Could someone help me with an Insert ? I'm trying to give insert in the DB but I have to convert the dateTimePicker pro to the right format, I do not know if it is exactly like this, I already tried google and tested it in several ways and none worked for me.
The first image is the INSERT, which is in a class.
The second image is the own button to insert.
The third image is the Database (yes I did in phpmyadmin of wamp msm pq is a very small and simple DB).
The error that happens when I try to insert is simply in that throw; Of the insert, and I think it's the question of help. Thank you to anyone who can help.
i just cant format the "Datav".
public void inserir_produtov()
{
try
{
string inserir1 = "INSERT INTO venda VALUES (null, '" + Datav.ToString("yyyy-MM-dd HH:mm:ss") + "', '" +
Id + "','" +
Quantidadev + "','" +
Valorv.ToString().Replace(',', '.') + "');";
bancodedados1.ExecutarComandos(inserir1);
}
catch
{
throw;
}
}
Here is the Button to insert:
private void btngravar1_Click(object sender, EventArgs e)
{
vendas.Id = int.Parse(txtidproduto.Text);
vendas.Quantidadev = int.Parse(txtquantidade2.Text);
vendas.Valorv = double.Parse(txtvalor.Text);
vendas.Datav = DateTime.Parse(dateTimePicker1.Text);
if (txtidvenda.Text == "")
{
vendas.inserir_produtov();
Limpar();
MessageBox.Show("Dados inseridos com sucesso.");
}
Use parameters instead so you don't need to format. This will also help prevent SQL injection too.
Have a look at this link:
SQL Insert Query Using C#
Related
I'm a beginner to C# so help would be much appreciated. I'm attempting to code a logging in system but I can only successfully log in with the first line of data (username=admin , password=admin). I can't seem to log in from other data in the database (username=bryan , password=123). This is the code.
searchOLEDB.CommandText = "SELECT * FROM LOGIN where Username='" + LoginIDTextBox.Text + "' AND Password='" + LoginPasswordTextBox.Text + "'";
searchOLEDB.Connection = cnnOLEDB;
OleDbDataReader dr = searchOLEDB.ExecuteReader();
if (dr.Read())
{
MessageBox.Show("Logged In");
}
else
{
MessageBox.Show("Invalid Password");
}
dr.Close();
First, you should never concatenate sql query like you did. This will allow SQL Injection. You should use parameters.
See this post for examples :
using parameters inserting data into access database
P.S. I would also recommend to not store password in clear into your database.
Hi I am using simple update query to update the password of a Admin login table it is not giving me any kind of error but it is not updating my record also.
please tell me what can be the problem
I am using Visual Studio 2012 | SQL SERVER 2008.
here is the Code.
protected void ButtonSubmit_Click(object sender, EventArgs e)
{
obj.OpenConection();
obj.ExecuteQueries("Update Admin_Login set Username='" + TextUsername.Text + "',Password='" + TextPassword.Text + "' where Username='" + TextUsername.Text + "'");
obj.CloseConnection();
}
=> ExecuteQueries() here is a function to execute different queries working fine every where even on other update queries but not here.
I have been working on a project related to database (.mdf). I have created some windows forms in visual studio using C#. Basically these forms work together to store, update and delete data from the Service Based Database i created.
The problem is when i build the project, it builds fine, no errors. It inserts a data provided from textboxes to the datagridview too as intended. But as soon as i stop the current debugging, and then rerun it again, all the data provided previously is lost from the datagridview!!
I cant understand why this is happening. anyone please help me. Im totally new to this stuff.. a bit of guidance would be heartily appreciated.
when i had previously used MySQL for the same purpose, the updated data would be permanently stored to the database, but since i migrated from the MySQL to SQL Server's Service Based Database, i get such confusing error.
......
void loadData()
{
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["baikalpik_bidhut_sewaConnectionString"].ToString());
SqlCommand cmd = new SqlCommand("SELECT SNo,Customer_ID, Citizenship_No, Name, Subscription_Date, Phone_No, Location,Locality,Bulbs,Deposit,Monthly_Charge FROM customerinformation;", con);
try
{
SqlDataAdapter adp = new SqlDataAdapter();
adp.SelectCommand = cmd;
DataTable dt = new DataTable();
adp.Fill(dt);
dataGridViewCustomerInformation.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void buttonAdd_Click(object sender, EventArgs e)
{
try
{
float m_chrg = Convert.ToInt64(textBoxBulbs.Text)*500;
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["baikalpik_bidhut_sewaConnectionString"].ToString());
SqlCommand cmd = new SqlCommand("INSERT INTO customerinformation(SNo,Customer_ID,Citizenship_No,Name,Subscription_Date,Location,Locality,Bulbs,Deposit,Phone_No,Monthly_Charge) values('" + textBoxSNo.Text + "','" + textBoxCustomerID.Text + "','" + textBoxCitizenshipNumber.Text + "','" + textBoxName.Text + "','" + textBoxSubscriptionDate.Text + "','" + textBoxLocation.Text + "','" + textBoxLocality.Text + "','" + textBoxBulbs.Text + "','" + textBoxDeposit.Text + "','" + textBoxPhoneNumber.Text + "','" + m_chrg + "')", con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
dt = new DataTable();
dt.Load(reader);
con.Close();
dataGridViewCustomerInformation.DataSource = dt;
loadData();
MessageBox.Show("Entry Added!");
fillListbox();
textBoxSNo.Clear();
textBoxBulbs.Clear();
textBoxCitizenshipNumber.Clear();
textBoxCustomerID.Clear();
textBoxDeposit.Clear();
textBoxLocality.Clear();
textBoxLocation.Clear();
textBoxPhoneNumber.Clear();
textBoxName.Clear();
textBoxSubscriptionDate.Clear();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
If you have your MDF listed in your project files then the property Copy To Output Directory handles how your MDF file is copied to the output directory (BIN\DEBUG or BIN\RELEASE).
If this property is set to Copy Always, then when you run your program a fresh copy of your database file is copied from the project folder to the output effectively destroying every data that you have inserted, modified, deleted in the previous run of your program.
The best solution to this dilemma is to add the MDF file as a permanent database inside your current install of Sql Server and adjust your connection string. And of course set the property to Copy Never
In alternative you could set to Copy if newer. This will allow to change the database schema inside the Server Explorer and let the Visual Studio IDE copy the new structure only after you have made changes.
UPDATE BUT IMPORTANT Not related to your actual question, but your insert query is a serious problem. Do not use string concatenation to build a sql command text. Particularly if the partial text comes from user input. You could face syntax errors (if someone places a single quote inside a text box) or worst, a Sql Injection problem (see here for a funny explanation)
To find good examples of Insert search for 'parametrized query'
I come to you after a lot of hours googling and reading other discussions about SQLite on StackOverflow, but I definitely can't find any explanation to my problem, so here it is :
The context :
I'm developping an application for iPad wich has to deal with some "large" amounts of data, in several occasions. In one of them, I must import points coordinates from a .kml file (Google's xml for geographical data) into my database, in order to reuse them later with a MKMapView and load them faster than by parsing xml when it needs to show a specific layer.
The details :
The import thing is quite easy : when dealing with those files, I'm only concerned with 2 tables :
One containing zones definitions and details : for the moment, an integer as an id, and a text for naming.
One containing two real for coordinate storage and an integer referencing the first table for knowing which zone point is part of.
So as long as reading my file, I first create an entry for the new zone, and then I insert points into the second table, with ID of the last zone created in the first table...nothing complicated!
But...
The problem :
After running fine a while, I get an exception from SQLite with the famous message "Unable to open the database file", and then it comes I can't do anything more with the database. This exception can randomly occur in the zone creation or the points insertion methods.
My reflexions :
Considering the numerous points in those files, I suspected memory or disk saturation but other parts of my app discarded those points (to my mind).
First, memory : it comes that when the exception occurs, the app is using about 10 or 12 MB of RAM. It can seems quite huge, but it's due to the ~10MB .kml file loaded in memory, so it's explainable. And above it all, the MKMapView thing of my app deals with tons of high-res tiles layers above map, and so leads to memory peaks which can afford 20 or even 25MB without making the iPad to crash.
Second, disk : when reseting my database and filling only the 2 tables described above, the db file size when the exception occurs is always about 2.2 or 2.5MB, but when I fill other tables (the other parts of my apps works well!) the db file is about 6 or 7MB, and the device doesn't complain at all.
So what?!
CPU-angryness and panic? I don't think so because some of the other tables of my database are filled at the same rythm without problem... and running my app in simulator crashes too, with a core i7 just laughing at the job.
SQLite bad use? There we go! To my mind, it's the only solution left! But I really can't understand what's going on here because I process my requests the same way I do in other app's parts which - repeating myself - work like a charm!
SQLite details :
I have a DB class which is a singleton I use to avoid creating/releasing an SqliteConnection object each request I do, and all my methods dealing with database are contained in this class to be sure I don't play with the connection anywhere else without knowing it. Here are concerned methods of this class :
public void saveZone(ObjZone zone) { //at this point, just creates an entry with a name and let sqlite give it a new id
lock (connection) { //SqliteConnection object
try {
openConnection();
SqliteCommand cmd = connection.CreateCommand();
cmd.CommandText = zone.id == 0 ?
"insert into ZONES (Z_NAME) values (" + format(zone.name) + ") ;" :
"update ZONES set Z_NAME = " + format(zone.name) + " where Z_ID = " + format(zone.id) + " ;";
cmd.ExecuteNonQuery();
if (zone.id == 0) {
cmd.CommandText = "select Z_ID from ZONES where ROWID = last_insert_rowid() ;";
zone.id = uint.Parse(cmd.ExecuteScalar().ToString());
}
cmd.Dispose();
}
catch (Exception e) {
Log.failure("DB.saveZone(" + zone.ToString() + ") : [" + e.GetType().ToString() + "] - " +
e.Message + "\n" + e.StackTrace); //custom Console.WriteLine() method with some formating
throw e;
}
finally {
connection.Close();
}
}
}
public void setPointsForZone(List<CLLocationCoordinate2D> points, uint zone_id) { //registers points for a given zone
lock (connection) {
try {
openConnection();
SqliteCommand cmd = connection.CreateCommand();
cmd.CommandText = "delete from ZONESPOINTS where Z_ID = " + format(zone_id);
cmd.ExecuteNonQuery();
foreach(CLLocationCoordinate2D point in points) {
cmd.CommandText = "insert into ZONESPOINTS values " +
"(" + format(zi_id) + ", " + format(point.Latitude.ToString().Replace(",", ".")) + ", "
+ format(point.Longitude.ToString().Replace(",", ".")) + ");";
cmd.ExecuteNonQuery();
cmd.Dispose();
}
}
catch (Exception e) {
Log.failure("DB.setPointsForZone(" + zone_id + ") : [" + e.GetType().ToString() + "] - " + e.Message);
throw e;
}
finally {
connection.Close();
}
}
}
And to be as clear as I can, here are some of the methods referenced in the two above (I use this custom openConnection() method because I use foreign keys constraints in most of my tables and cascading behaviours are not enabled by default, but I need them.) :
void openConnection() {
try {
connection.Open();
SqliteCommand cmd = connection.CreateCommand();
cmd.CommandText = "PRAGMA foreign_keys = ON";
cmd.ExecuteNonQuery();
cmd.Dispose();
}
catch (Exception e) {
Log.failure("DB.openConnection() : [" + e.GetType().ToString() + "] - " + e.Message);
throw e;
}
}
public static string format(object o) {
return "'" + o.ToString().Replace("'", "''") + "'";
}
Well, sorry for the novel, I may already thank you for reading all that stuff, no?! Anyway, if I missed something that could be useful, let me know and I'll document it as soon as possible.
I hope someone will be able to help me, anyway, thank you by advance!
(And my apologies for my poor frenchie's english.)
EDIT
My problem is "solved"! After a few changes for debugging pourposes, no big modifications, and no success, I put back the code in the state I posted it... and now it works. But I really would appreciate if some someone could give me an explanation of what may have happened! It seems like SQLite behaviour (on iPad at least - never used it anywhere else) can be quite obscure at some times... :/
I wouldn't cross my fingers for this but I would try two things:
If possible, pre-process the KML file to a second SQLite database and use this database to import data in the main database (thinking of lower memory/processor requirements)
Transaction the imported data in small batches.
HTH
EDIT: you might have checked this already, but anyway: unable to open database.
Hey guys, I'm just doin' practise Program to read,write data to Access DB in C# and i'm having a problem in writing data to Access DB though i'm able to read data i.e fetchin' is working fine but when i insert data my "ExecuteNonQuery" is working fine i mean without ne error but when open the Access DB the data is not there.... here is the code what m tryin' to do...
//// Function For ExecuteNonQuery
public static bool ExecuteNonQuery(string Query)
{
OleDbCommand oledbCommand = new OleDbCommand(Query, connection);
if (connection.State == ConnectionState.Open)
connection.Close();
try
{
connection.Open();
if (oledbCommand.ExecuteNonQuery() > 0)
return true;
else
return false;
}
catch (Exception)
{
return false;
}
finally
{
connection.Close();
}
}
This below code is for Adding Data which gets fired on "Add" Button Press
private void btnAdd_Click(object sender, EventArgs e)
{
simOperator.aim_network_name = txtAimNetNm.Text;
simOperator.network_id = txtOxiNetID.Text;
simOperator.network_name = txtNetName.Text;
simOperator.pack_id = txtPackID.Text;
simOperator.pack_name = txtPackName.Text;
SimOperator.Add(simOperator);
fillText();
}
public void fillText()
{
txtResult.Text = "";
SimOperator[] simOperatorList = SimOperator.GetAllOperators();
foreach (SimOperator sm in simOperatorList)
{
txtResult.Text += Program.operator_id + " " + sm.aim_network_name + " " + sm.network_name + " " + sm.network_id + " " + sm.pack_id + " " + sm.pack_name + "\r\n";
}
}
Here's the "Add" Function
string Query = string.Format("insert into {0}({2}) values({1});", calledObject.Name, PropertyValue,PropertyName);
ExecuteNonQuery(Query);
Actuall SQL query is:
insert into SimOperator(aim_network_name,network_id,network_name,pack_id,pack_name) values('FiveNet','2563','FiveNet-Kurla','1236','5236');
Yeah and My Connection String
static OleDbConnection connection = new OleDbConnection(System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"]);
App.config file contains string as
add key="ConnectionString" value="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\AutoMobileRecharge.mdb;User Id=; Password=;Persist Security Info=True"
The thing m not getting is I have put a Text-Area just beside all the inside fields textboxes so that i can see what is getting inserted, so when insert data that text-area shows the data perfectly but when i open the access db, then theres no data in that, when i close my application and again i ran it then that text-area is empty...this sounds wierd to me.. Any one outthere have faced this kind a problem please help me out here..
Are you doing it during debug ? in that case look if there's an mdf file inside debug folder and if it contains the data you've just inserted. Vs copy some file to debug folder when you run the app in that mode. If i remember correctly there's an option to tell vs not to copy files when debugging