I'm trying to write a program for my exam. I have to use and work with database, i've written some code and encountered a problem. Database is not updating. When I execute my application everything works perfectly, I add some info and it appears in my dataGridView, but when I go to the table in database that i've been updating and select "Show table data", it's empty.
This is function that inserts data into my database.
static public void Insert(string _imonesPav, string _imonesKodas, string _sutartiesPradzia, string _sutartiesPabaiga)
{
try
{
connection.Open();
SqlCommand command = new SqlCommand("INSERT INTO Tiekejai VALUES (#ImonesPav, #ImonesKodas, #SutartiesPradzia, #SutartiesPabaiga)", connection);
command.Parameters.AddWithValue("#ImonesPav", _imonesPav);
command.Parameters.AddWithValue("#ImonesKodas", _imonesKodas);
command.Parameters.AddWithValue("#SutartiesPradzia", _sutartiesPradzia);
command.Parameters.AddWithValue("#SutartiesPabaiga", _sutartiesPabaiga);
command.ExecuteNonQuery();
}
catch (SqlException exception)
{
MessageBox.Show(exception.ToString());
}
finally
{
connection.Close();
}
}
And this is how i use it.
private void updateDatabase_Click(object sender, EventArgs e)
{
SQLFunkcijos.Insert(imonesVardas.Text, imonesKodas.Text, sutartPradzia.Text, sutartPabaiga.Text);
SQLFunkcijos.Refresh(this.dataGridView1);
}
Refresh function is used to update data in dataGridView in real time.
So the question would be, what am i doing wrnog? Why table in database is not updating.
P.S. I've tried all Copy to Output options, it works only with Copy if newer.
EDIT1: Refersh function.
static public void Refresh(DataGridView _dataGridView)
{
try
{
connection.Open();
SqlDataAdapter dataAdapter = new SqlDataAdapter("Select * FROM Tiekejai", connection);
DataTable dataTable = new DataTable();
dataAdapter.Fill(dataTable);
_dataGridView.DataSource = dataTable;
}
catch(SqlException exception)
{
MessageBox.Show(exception.ToString());
}
finally
{
connection.Close();
}
}
EDIT2: Problem solved! I was just using bad connection string. Thanks for everyones help.
Related
I'm trying to copy some columns from one table located on the MySQL Server, to a local MySQL database using C#. How can I do it ?
I'm not sure if i should use MySQLDataAdapter or Bulk Copy (which i don't understand much).
Bulk copy would be an easier method. It takes a previously created datatable and uploads it to the database.
You can use the following code to help. The below code allows you to return a datatable:
public DataTable FillTable(string sql)
{
MySqlCommand sqlQuery = new MySqlCommand();
cmd.Connection = ;// insert the connection details of the DB to transfer FROM
cmd.CommandText = sql;
DataTable dt = new DataTable();
try
{
conn.Open();
dt.Load(cmd.ExecuteReader());
conn.Close();
}
catch (SqlException ex)
{
Console.WriteLine("fillTable: "+ ex.Message);
}
return dt;
}
Then using the following you can send the data over to your new database:
Datatable newTable = FillTable("SELECT * FROM MyOldTable");
using (MySqlBulkCopy destination = new MySqlBulkCopy("MyNewDatabaseConnection String"))
{
destination.DestinationTableName = "myNewTable";
try
{
destination.WriteToServer(newTable);
}
catch (Exception Ex)
{
Console.WriteLine(Ex.Message);
}
}
Reference MSDN
I'm working on ASP.NET web aplication. I'm making it to be MVC and i have a problem with controler class. When i want to populate a drop down list with elements from my SQL database, class is working but only one instance of class with just one drop down list. When i use one class to populate 2 or more drop down lists it doesn't work and VS is not raising any errors. The controler class works, and it can populate drop down list, but just only one drop down list when page is loaded. So to work i have to make an instance of controler class for every drop down list. Please, can someone explain to me why won't work...
this is my DbBroker:
public DataTable VratiKategorije()
{
DataTable kategorije = new DataTable();
using (cn)
{
try
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM KategorijaLeka", cn);
adapter.Fill(kategorije);
}
catch (Exception err)
{
//
}
}
return kategorije;
}
And this is my Controler class which is using DbBroker:
public void VratiKategorije(DropDownList ddlKategorije){
try
{
ddlKategorije.DataSource = dbB.VratiKategorije();
ddlKategorije.DataTextField = "Naziv";
ddlKategorije.DataValueField = "ID_Kategorije";
ddlKategorije.DataBind();
}
catch (Exception err)
{
//Handle the err
}
ddlKategorije.Items.Insert(0, new ListItem("", ""));
}
And this is on Load_Page():
protected void Page_Load(object sender, EventArgs e)
{
KontrolerLeka kl = new KontrolerLeka();
kl.VratiKategorije(kategorijaLeka);
}
I found what was the problem. Ok, so when you use using() function with adapter there is no closing connection to database so when same function is called it can't populate another drop down list because the connection from last drop down list function is not closed. Insted of that code in DbBroker i used this and it worked! "pokreniDBtransakciju()" use cn (sql connection string) and after taking Record Set from database the connection is closed using "cn.Close()" which solved all problems.
DbBroker:
public DataTable Uzmi()
{
DataTable dt;
dt = new DataTable();
SqlCommand sc = new SqlCommand();
try
{
sc.CommandText = "SELECT * FROM KategorijaLeka";
sc.Connection = pokreniDBTransakciju();
SqlDataReader reader;
reader = sc.ExecuteReader();
dt.Load(reader);
cn.Close();
}
catch (SqlException e)
{
Console.WriteLine("GRESKA!!!" + e);
return null;
}
return dt;
}
Apologies if this is somewhat of an elementary question... .net newb here thrown in at the deep end.
I have created a stored procedure to return a record which I am executing as below. When I inspect "r" with a breakpoint in Visual Studio express, my data is returned correctly.
MyPage.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
var dd = dealerDetails();
}
protected DataTable dealerDetails()
{
SqlConnection cn;
SqlCommand cmd;
using (cn = new SqlConnection(Settings.Server.ConnectionString))
{
cn.Open();
cmd = new SqlCommand("spMyStoredProcedure", cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#strslug", SqlDbType.NVarChar, -1).Value = Page.Request.QueryString["_slug"];
JJ.Diagnostics.Tracer.Trace(cmd);
try
{
IDataReader r = cmd.ExecuteReader();
while (r.Read())
{
??????
}
r.Close();
return ?????;
}
catch (SqlException exSql)
{
// Make an event log entry of the exception
EventLogController.LogException(exSql);
throw;
}
catch (Exception ex)
{
// Make an event log entry of the exception
EventLogController.LogException(ex);
throw;
}
}
}
When I simply try to return r, I get an error:
Cannot inplicityly convert type 'System.Data.IDataReader' to 'System.Data.DataTable'.
An explicity conversion exists (are you missing a cast?)
I would like to be able to access the results from this stored procedure in MyPage.aspx. I'd assume that I could do this with <%=dd.propname%> am I correct in this or would it require any additional steps?
Please let me know if I've ommited any important information here.
Use a data adapter to fill a data table and return that. If your stored procedure is returning only the data that is required. I don't see any reason to iterate through every column and explicitly define them. A SqlDataAdapter will fill a DataTable for you without hard coding and adding the row values.
HERE is some reading and examples of SqlDataAdapters.
using (SqlDataAdapter da = new SqlDataAdapter(cmd, cn)
{
DataTable dt = new DataTable("TableName");
da.Fill(dt);
return dt;
}
Entire Code:
// Utilize the using directive on any disposable objects so you aren't
// left with garbage.
using (SqlConnection cn = new SqlConnection(Settings.Server.ConnectionString))
using (SqlCommand cmd = new SqlCommand("spMyStoredProcedure", cn))
{
cmd.CommandType = CommandType.StoredProcedure;
// define your parameter here, just personal preference, but makes debugging
//easier in my opinion.
string slug = Page.Request.QueryString["_slug"];
// Use the newer .AddWithValue command.
cmd.Parameters.AddWithValue("#strslug", slug);
JJ.Diagnostics.Tracer.Trace(cmd);
try
{
// SqlDataAdapter will automatically open/close your connection for you,
// however, for future reference, try to open your connection only when
// it is required to be opened. This will reduce your connection time/
// server strain.
// cn.Open();
using (SqlDataAdapter da = new SqlDataAdapter(cmd, cn)
{
// Data adapter will automatically fill your returned data table.
DataTable dt = new DataTable("TableName");
da.Fill(dt);
return dt;
}
}
catch (SqlException exSql)
{
// Make an event log entry of the exception
EventLogController.LogException(exSql);
throw;
}
catch (Exception ex)
{
// Make an event log entry of the exception
EventLogController.LogException(ex);
throw;
}
}
From this point you may access your data like this:
protected void Page_Load(object sender, EventArgs e)
{
DataTable dd = dealerDetails();
// if more than one row is expected you can use the for loop
// if not, just access them directly.
for (int i = 0; i < d.Rows.Count - 1; i++)
{
// Jump straight to here if you are positive you will only
// return 1 row of data.
string ColumnName1 = dd.Rows[i]["ColumnName1"].ToString();
string ColumnName2 = dd.Rows[i]["ColumnName2"].ToString();
}
}
According to your dealerDetails method signature - return value is DataTable. So you can't return DataReader because it is not derived from DataTable.
You need to create DataTable and its columns, and fill table while reading from dataReader.
Something like this
using(var r = cmd.ExecuteReader())
{
var dt = new DataTable();
dt.Columns.Add("Column1_Name", typeof(column1_Type));
dt.Columns.Add("Column2_Name", typeof(column2_Type));
while (r.Read())
{
var dro = dt.NewRow();
dro["Column1_Name"] = somevalue_from_reader;
dro["Column2_Name"] = somevalue_from_reader;
dt.Rows.Add(dro);
}
r.Close();
return dt;
}
I am new to C# and have been working on a program for work. A simple ticketing program as a backup when the primary goes down. I don't have a server to run a database on so I have been using sqlite. This works great since I don't need to install anything. I would like to set it up to save the database file for each users program to save to a network location with a unique name for the database file. I have figured out how to set the save location of the database but not give the file a name. I would like to use the name of the current logged in user which is already unique and displays when the program runs, it is also added to the database when a new ticket is saved. The program checks the file location and if the database does not exist creates it.
public partial class Ticket_Contingency : Form
{
SQLiteConnection con;
SQLiteDataAdapter da;
SQLiteCommand cmd;
DataSet ds;
DataTable dt;
int id;
string userName = Environment.UserName;
}
public Ticket()
{
InitializeComponent();
AppDomain.CurrentDomain.SetData("DataDirectory", Environment.GetFolderPath(Environment.SpecialFolder.Personal));
private void Form1_Load(object sender, EventArgs e)
{
//loads the saved username from App.config
usernametextBox.Text = userName;
AppDomain.CurrentDomain.SetData("DataDirectory", Properties.Settings.Default.folderdb);
dblabel.Text = Properties.Settings.Default.folderdb;
//Diables Autovalidation
this.AutoValidate = AutoValidate.Disable;
if (!File.Exists("|DataDirectory|incidentdb.sqlite"))
try
{
con = new SQLiteConnection(#"Data Source=|DataDirectory|incidentdb.sqlite;Version=3;New=True;Compress=True;");
con.Open();
cmd = con.CreateCommand();
cmd.CommandText = "CREATE TABLE 'contacts' ('Id' INTEGER PRIMARY KEY NOT NULL DEFAULT (0) ,'firstname' VARCHAR,'lastname' VARCHAR,'mi' CHAR,'email' VARCHAR,'phone' VARCHAR,'ext' CHAR,'visn' CHAR,'site' VARCHAR,'department' VARCHAR,'desklocation' VARCHAR,'notes' VARCHAR,'template' VARCHAR,'priority' CHAR,'summary' VARCHAR, 'status' CHAR, 'timestamp' DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, 'username' VARCHAR)";
cmd.ExecuteNonQuery();
con.Close();
Form1_Load(this, null);
}
catch (SQLiteException ex)
{
// Log the exception
{
}
//Tries to connect to the local Database. Returns error message on failure
try
{
con = new SQLiteConnection(#"Data Source=|DataDirectory|incidentdb.sqlite;Version=3;");
con.Open();
da = new SQLiteDataAdapter("Select ID, firstname as 'firstname', lastname as 'lastname', summary as 'summary', timestamp as 'timestamp' from contacts ORDER by ID ASC", con);
ds = new System.Data.DataSet();
da.Fill(ds, "Person_Details");
dataGridView1.DataSource = ds.Tables[0];
con.Close();
Clear_Form(this, null);
}
catch (SqlException)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
Application.ExitThread();
}
}
}
What I would like to do is replace
if (!File.Exists("|DataDirectory|incidentdb.sqlite"))
with something like
if (!File.Exists("|DataDirectory|" + userName + ".sqlite"))
I know that doesn't work but I really have no idea how to go about this. I have searched everywhere but can only come up with results that look like the original code
if (!File.Exists("|DataDirectory|incidentdb.sqlite")
I would really appreciate some help. Like I said I am new to this. Most of my other issues were solved with research but this is beyond me. Thanks!
This code reads and updates the form fine when I run the program, but it does not update when I edit the values in the datagridview and click update.
I am following a video tutorial series and this code does work in the video to update the table.
Question: Why does it not update when I edit the values in the datagridview?
using System.Data.SqlServerCe;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
private SqlCeConnection conn; // Our Connection
private SqlCeDataAdapter da; // Data Adapter
private DataSet ds; // Dataset
private string sTable = "authors"; // Table Name
public Form1()
{
InitializeComponent();
InitData(); // Get the Data
dataGridView1.DataSource = ds;
dataGridView1.DataMember = sTable;
}
public void InitData()
{
try
{
// Instantiate the Connection
conn = new SqlCeConnection("Data Source=|DataDirectory|\\Database1.sdf");
// Instantiate a new DataSet
ds = new DataSet();
// init SQLDataAdapter with select command and connection
da = new SqlCeDataAdapter("SELECT id, name, email FROM " + sTable, conn);
// Automatically generates insert, update and delete commands
SqlCeCommandBuilder cmdBldr = new SqlCeCommandBuilder(da);
// Fill in the dataset view
da.Fill(ds, sTable);
}
catch (Exception excep)
{
MessageBox.Show("Exception: " + excep.Message);
}
}
private void button1_Click(object sender, EventArgs e)
{
try
{
da.Update(ds, sTable);
}
catch (Exception excep)
{
MessageBox.Show(excep.Message);
}
}
}
}
The program compiles, but the update command is not working to update the database on click of button1.
This may seem silly but have you checked that the user name you are using to connect has write permissions and not just read-only on the database?