updating information from database - error db locked - c#

I created an app like a quiz.. When I try to show the score in the labels I got this error:
An unhandled exception of type 'System.Data.SQLite.SQLiteException' occurred in System.Data.SQLite.dll Additional information: database is locked database is locked
I know which is the problem, but I don`t know how to solve it.
The problem is for sure in the Menu Form (the 'highest parent'). And I know that because the app updates the database from the Quiz form, but when it comes back and read the database so that I can change the labels I got that error. ONLY IF THE update_score() is both in Meniu() (or even in Meniu_Load() ) and after the .ShowDialog()
update_score() -reads database and change labels
Conclusion: I can not show in labels the highest scores both times: when I open the app and when comes back from the quizz form..So, I have to put in comment the update_score after the showdialog (the user won`t know the score when it comes back) or in the Meniu /Meniu_Load (it does not show at the beginning).
How can I solve it?
The Menu code:
public partial class Meniu : Form
{
SQLiteConnection con;
public bool con_opened = false; // tin minte daca am deschis conexiunea
public int bs_lit=0, bs_info = 0;
public Meniu()
{
//this.StartPosition = FormStartPosition.CenterScreen;
InitializeComponent();
con_opened=false;
update_score();
}
private void Meniu_Load(object sender, EventArgs e)
{
//con_opened=false;
//update_score();
}
public void db1_read()
{
if (con_opened == false)
{
con = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");//Version=3;
con_opened = true;
con.Open();
}
string sql = "select * from bestscore WHERE materie LIKE 'literatura'";
SQLiteCommand command = new SQLiteCommand(sql, con);
SQLiteDataReader reader = command.ExecuteReader();
reader.Read();
bs_lit = Int32.Parse(reader[1].ToString());
command.Dispose();
sql = "select * from bestscore WHERE materie LIKE 'informatica'";
SQLiteCommand cmd = new SQLiteCommand(sql, con);
SQLiteDataReader rdr = cmd.ExecuteReader();
rdr.Read();
bs_info = Int32.Parse(rdr[1].ToString());
cmd.Dispose();
con.Close();
con_opened = false;
}
private void update_score()
{
db1_read();
lbl_bs_info.Text = bs_info.ToString();
lbl_bs_lit.Text = bs_lit.ToString();
}
private void btn_literatura_testare_Click(object sender, EventArgs e)
{
testare flit = new testare();
this.Hide();
flit.reveal = false;
flit.materie = "literatura";
flit.ShowDialog();
update_score(); // if the function is here and in Meniu()
// or Meniu_load()I receive the error
// if it`s just one of them
//it works just fine
if (flit.reveal == true)
this.Show();
else
Application.Exit();
}
}
Thank you!

I found the answer: I didn`t Dispose the readers. Now it works.
public void db1_read()
{
if (con_opened == false)
{
con = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");//Version=3;
con_opened = true;
con.Open();
}
string sql = "select * from bestscore WHERE materie LIKE 'literatura'";
SQLiteCommand command = new SQLiteCommand(sql, con);
SQLiteDataReader reader = command.ExecuteReader();
reader.Read();
bs_lit = Int32.Parse(reader[1].ToString());
command.Dispose();
reader.Dispose();
sql = "select * from bestscore WHERE materie LIKE 'informatica'";
SQLiteCommand cmd = new SQLiteCommand(sql, con);
SQLiteDataReader rdr = cmd.ExecuteReader();
rdr.Read();
bs_info = Int32.Parse(rdr[1].ToString());
cmd.Dispose();
rdr.Dispose();
con.Close();
con_opened = false;
}

Related

How to load an image that is stored in a database into a picturebox object with C# and SQL

When doubling clicking a row in datagrid object within the following windows form, the relevant information properly displays in a secondary form.
However I am not sure how to make it so that the image also displays in picturebox within the Student Form.
Here is the code so far:
public bool IsUpdate { get; set; }
private void StudentForm_Load(object sender, EventArgs e)
{
//For Update Process
if (this.IsUpdate == true)
{
using (SqlConnection con = new SqlConnection(AppConnection.GetConnectionString()))
{
using (SqlCommand cmd = new SqlCommand("usp_Student_ReloadDataForUpdate", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#StudentName", this.StudentName);
if (con.State != ConnectionState.Open)
con.Open();
DataTable dtStudent = new DataTable();
SqlDataReader sdr = cmd.ExecuteReader();
dtStudent.Load(sdr);
DataRow row = dtStudent.Rows[0];
StudentNameTextBox.Text = row["StudentName"].ToString();
AgeTextBox.Text = row["Age"].ToString();
GenderTextBox.Text = row["Gender"].ToString();
DescriptionTextBox.Text = row["Description"].ToString();
//IdPictureBox.Image = row["Image"].???
SaveButton.Text = "Update Student Information";
DeleteButton.Enabled = true;
}
}
}
This follow is the stored procedure for the method above:
CREATE PROCEDURE usp_Student_ReloadDataForUpdate
(
#StudentName NVARCHAR(200)
)
AS
BEGIN
SELECT [StudentId]
,[StudentName]
,[Age]
,[Gender]
,[Description]
,[Image]
FROM [dbo].[Students]
WHERE StudentName = #StudentName
END
This is how the data is saved in the database
private void SaveButton_Click(object sender, EventArgs e)
{
if(IsFormValid())
{
//Do Update Process
using (SqlConnection con = new SqlConnection(AppConnection.GetConnectionString())) //connect to database using AppConnection class and GetConnectionString method
{
using (SqlCommand cmd = new SqlCommand("usp_Student_InsertNewStudent", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#StudentName", StudentNameTextBox.Text.Trim());
cmd.Parameters.AddWithValue("#Age", AgeTextBox.Text.Trim());
cmd.Parameters.AddWithValue("#Gender", GenderTextBox.Text.Trim());
cmd.Parameters.AddWithValue("#Description", DescriptionTextBox.Text.Trim());
var image = IdPictureBox.Image;
using (var ms = new MemoryStream())
{
image.Save(ms, image.RawFormat);
cmd.Parameters.Add("#Image", SqlDbType.VarBinary).Value = ms.ToArray();
}
cmd.Parameters.AddWithValue("#CreatedBy", LoggedInUser.UserName);
if (con.State != ConnectionState.Open)
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Student is successfully updated in the database.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
ResetFormControl();
}
}
}
The data stored is a byte[] (Varbinary). You should convert it to an Image:
var pic = (byte[])row["Image"];
if (pic != null)
{
using (MemoryStream ms = new MemoryStream(pic))
{
IdPictureBox.Image = Image.FromStream(ms);
}
}
PS: I am not commenting on the rest of your code, like you shouldn't use AddWithValue but Add.

SQL DataReader: Invalid attempt to read when no data is present to label

I am trying to use a SqlDataReader to run queries on two tables where the 1st column in the Selection table is a foreign key referencing to the Items table, and then display the results in labels, but I keep getting the error:
Invalid attempt to read when no data is present.
Here is my code:
public partial class Read : System.Web.UI.Page
{
SqlConnection conn = new SqlConnection(#"data source = localhost; integrated security = true; database = dev_handin1");
SqlCommand cmd = null;
SqlDataReader rdr = null;
string sqlsel = "SELECT MainItemId FROM Selection";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetInfo();
}
}
private void GetInfo() {
try
{
cmd = new SqlCommand(sqlsel, conn);
conn.Open();
sqlsel = "SELECT * FROM Items WHERE ItemId = MyMainItem";
rdr = cmd.ExecuteReader();
var MyMainItem = rdr[0];
while (rdr.Read())
{
LabelCategory1.Text = rdr[1].ToString();
LabelHeadline1.Text = rdr[2].ToString();
LabelText1.Text = rdr[3].ToString();
LabelJoke1.Text = rdr[4].ToString();
}
}
catch (Exception ex)
{
LabelMessage1.Text = ex.Message;
}
finally
{
rdr.Close();
conn.Close();
}
}
}
}
I'm pretty new at this so please bear with me.

Fill public strings with Database info from userlogin

I have created a class that gets the user details from DB to strings (username,userpassword,usernr,usersubco).
What i want to happen is that those strings fill with the info from the user I login with.
public class Details
{
public connectionUser constring = new connectionUser();
public string Technr;
public string Techpass;
public string Techname;
public string Techsubco;
public Details()
{
using (SqlConnection con = new SqlConnection(constring.source))
{
myInlogForm myI = new myInlogForm();
con.Open();
SqlCommand cmd = new SqlCommand("select * from techs where technr=#technr", con);
cmd.Parameters.Add(#"technr", SqlDbType.Int).Value = myI.technr;
cmd.ExecuteNonQuery();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Technr = reader[0].ToString();
Techpass = reader[1].ToString();
Techname = reader[2].ToString();
Techsubco = reader[3].ToString();
break;
}
con.Close();
}
MessageBox.Show(Techname + Technr + Techpass + Techsubco);
}
myI = usercontrol (inlogscreen)
myIn.technummer is a public string that get value on loginbutton from textbox.
when I push login I got the message box from this class above (empty) and following error :
UPDATED !!!
System.Data.SqlClient.SqlException: 'The parameterized query
'(#technr int)select * from techs where technr=#technr' expects the
parameter '#technr', which was not supplied.'
public event EventHandler<EventArgs> callMenu; // oproep door mainform
public event EventHandler<EventArgs> callDash; // oproep door mainform
public int technr;
private void loginBtn_Click(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(cUser.source.ToString()))
{
con.Open();
SqlCommand cmd = new SqlCommand("select technr,techcode from techs where technr=#technr and techcode=#techcode", con);
cmd.Parameters.Add(#"technr",SqlDbType.Int).Value = userTxb.Text;
cmd.Parameters.Add(#"techcode",SqlDbType.VarChar).Value = passTxb.Text;
cmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0 && callMenu != null && callDash != null) // checks login is juist
{
callMenu(this, new EventArgs());
callDash(this, new EventArgs());
technr = int.Parse(userTxb.Text);
}
else
{
MessageBox.Show("Foutieve gegevens");
}
con.Close();
}
}
try it in this way
cmd.Parameters.Add(#"#technr", SqlDbType.Int).Value = myI.technr;

C# update statement not updating when update button clicked

i am creating c# project so far insert and delete buttons are working but when i hit update button it gives data has not been updated and i cant see what is wrong with my code please help
public bool Update(Classre c)
{
bool isSuccess = false;
SqlConnection conn = new SqlConnection(myconnstring);
try
{
string sql = "UPDATE Class SET ClassName=#ClassName,ClassLevel=#ClassLevel WHERE ClassID=#ClassID";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#ClassName", c.ClassName);
cmd.Parameters.AddWithValue("#ClassLevel", c.ClassLevel);
conn.Open();
int rows = cmd.ExecuteNonQuery();
if (rows > 0)
{
isSuccess = true;
}
else
{
isSuccess = false;
}
}
catch (Exception ex)
{
}
finally
{
conn.Close();
}
return isSuccess;
}
and this is my update button code where i call the class that holds my update code
private void button3_Click(object sender, EventArgs e)
{
c.ClassID = int.Parse(textBox1.Text);
c.ClassName = textBox2.Text;
c.ClassLevel = comboBox1.Text;
bool success = c.Update(c);
if (success == true)
{
// label4.Text = "Data Has been updated";
MessageBox.Show("Data Has been updated");
DataTable dt = c.Select();
dataGridView1.DataSource = dt;
}
else
{
//label4.Text = "Data Has not been updated";
MessageBox.Show("Data Has not been updated");
}
}
I would prefer to use a stored procedure instead of pass through sql but you could greatly simplify this. As stated above your try/catch is worse than not having one because it squelches the error.
public bool Update(Classre c)
{
USING(SqlConnection conn = new SqlConnection(myconnstring))
{
string sql = "UPDATE Class SET ClassName = #ClassName, ClassLevel = #ClassLevel WHERE ClassID = #ClassID";
USING(SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add("#ClassName", SqlDbType.VarChar, 4000).Value = c.ClassName;
cmd.Parameters.Add("#ClassLevel", SqlDbType.Int).Value = c.ClassLevel;
cmd.Parameters.Add("#ClassID", SqlDbType.Int).Value = c.ClassID;
conn.Open();
int rows = cmd.ExecuteNonQuery();
return rows > 0;
}
}
}

Getting Invalid syntax near keyword where

I am on the verge of finishing a web-project similar to nike+ and runkeeper, it is a prototype for a company make running devices, anyhow I have stumbled upon a problem here, and I am getting a error message that says Invalid syntax near keyword WHERE. I cannot for the life of me figure it out.
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Email"] == null) //If user is not logged in, send to startpage
{
Response.Redirect("~/UserPages/Default.aspx");
}
else if (!IsPostBack)
{
//User info is selected from DB and put in textboxes
SqlConnection con1 = new SqlConnection(ConfigurationManager.ConnectionStrings["jaklin11ConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand("SELECT * FROM [Users] WHERE Email = #Email", con1);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Email", Session["Email"].ToString());
using (con1)
{
con1.Open();
SqlDataReader rdr = cmd.ExecuteReader();
if (rdr.Read())
{
imgProfileImageProfile.ImageUrl = rdr["ProfileImage"].ToString();
textProfileImageProfile.Text = rdr["ProfileImage"].ToString();
textFirstNameProfile.Text = rdr["FirstName"].ToString();
textLastNameProfile.Text = rdr["LastName"].ToString();
textHeightProfile.Text = rdr["Height"].ToString();
textWeightProfile.Text = rdr["Weight"].ToString();
textPasswordProfile.Text = rdr["Password"].ToString();
textBirthdateProfile.Text = rdr["Birthdate"].ToString();
textAreaCode.Text = rdr["AreaCode"].ToString();
textTown.Text = rdr["Town"].ToString();
ddlGenderProfileEdit.Text = rdr["Gender"].ToString();
}
}
}
}

Categories