I'm developing a library system for my project. My adviser ask me to compute a fine for overdue books. I have 3 textboxes one for student id, book title and isbn, and I also have two datetime pickers; one is for date and one for due date. I want a create a command that will compute a fine if the borrower didn't return the book on duedate and will input the fine in my table 'Borrowbook' column 'Penalty'.
This is my code:
string constring = ("Data Source=.\\SQLEXPRESS;Integrated Security=True");
SqlConnection con = new SqlConnection(constring);
con.Open();
SqlCommand cmd = new SqlCommand("SELECT [Student ID], ISBN, Title, Date, [Due Date], Penalty FROM Borrowbook;", con);
try
{
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = cmd;
DataTable Records = new DataTable();
sda.Fill(Records);
BindingSource bsource = new BindingSource();
bsource.DataSource = Records;
dataGridView1.DataSource = bsource;
sda.Update(Records);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
if (dateTimePicker2.Value < DateTime.Now)
{
cmd.CommandText = "INSERT INTO Borrowbook (Penalty) VALUES (#Penalty)";
SqlParameter p1 = new SqlParameter("#Penalty", SqlDbType.Date);
p1.Value = 50;
cmd.Parameters.Add(p1);
cmd.ExecuteNonQuery();
}
}
This code is not working but it runs properly and didn't have any errors. But I think this is the idea for my code. I put this code in the button where also my datagridview will show my data.
You haven't executed your query.
You need:
cmd.ExecuteNonQuery();
You will also need a SqlConnection object that points to the correct SQL Server database.
As an additional note, your database schema looks a bit fuzzy, how would you know what person incurred the penalty? You haven't inserted any other identifier, just the penalty amount.
Related
I'm writing a SQL command to insert new record into a SQL Server database using an ASP.NET website, but it's not working, although it's preserving the id of an auto-increment column.
When the auto-increment value is 5, and then I try to insert a new row using Management Studio, it does insert the record with id=7.
Thanks to anyone who tells me what I'm doing wrong here
Here is the code:
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter();
try
{
cmd.CommandText = "insert into Bill values (#car, #date, #client, #speedometer, #employee, #notes)";
cmd.Parameters.AddWithValue("#car", carid);
cmd.Parameters.AddWithValue("#date", txt_bill_date.Value);
cmd.Parameters.AddWithValue("#client", cmb_client_name.Value);
cmd.Parameters.AddWithValue("#speedometer", txt_car_gas.Value);
cmd.Parameters.AddWithValue("#employee", cmb_emp.Value);
cmd.Parameters.AddWithValue("#notes", txt_notes.Value);
cmd.ExecuteNonQuery();
cmd.CommandText = "select top 1 bill_id from Bill order by bill_id DESC";
DataTable inserted = new DataTable();
sda.Fill(inserted);
if (inserted.Rows.Count > 0)
{
billid = inserted.Rows[0]["bill_id"].ToString();
contractid.Values["id"] = inserted.Rows[0]["bill_id"].ToString();
Response.Redirect("BillContracts.aspx");
}
}
catch(Exception ex)
{
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", "swal('خطأ', '" + ex.Message + "', 'error')", true);
}
Sorry for the inconvenience guys
your advice of putting a break point on the catch saved my day
the problem was with the columns type
apparently be mistake i added an int column for a string value
i apologize again if i didn't do this right
I created an app for inserting specific data into database and it works fine.
However, when i try to view that data, DataGridView shows just some of those fields.
I stucked here. I tried to delete DataGridView and write code again, but it didn't helped.
private void displayData()
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\me\Documents\DataB.mdf;Integrated Security=True;Connect Timeout=30";
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM dbo.Users ";
cmd.ExecuteNonQuery();
DataGrid.Update();
DataSet dt = new DataSet();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
DataGrid.DataSource = dt;
conn.Close();
}
I expected completely filled DataGridView, but some fields are empty.
I can see name, username, date of birth, than 5 empty cells, then again i can see salary, education and so on..
I am trying to make c# program, where I have to make a database report to be previewed at the datagridview. Data will be selected using the datetimepicker. I have written the code, it works but then if the date selected is of different months. No records appear
void FilterDBbtnClick(object sender, EventArgs e)
{
MySqlConnection conn = new MySqlConnection();
conn = new MySqlConnection(cs);
string data = "SELECT `Date`, `Process`, `Actual`, `Target` FROM `database` WHERE `Date` BETWEEN '"+this.fromDatePicker.Value+"' AND '"+this.toDatePicker.Value+"' order by `Date` desc";
MySqlCommand cmd = new MySqlCommand(data, conn);
cmd.Connection.Open();
try
{
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmd;
DataSet dt = new DataSet();
sda.Fill(dt);
BindingSource bsource = new BindingSource();
bsource.DataSource = dt;
mondeDataTable.DataSource = dt.Tables[0];
sda.Update(dt);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
cmd.Connection.Close();
}
please help me check my code and tell me what might be wrong or missing.
Use profiler to check the query that hits the DB. I suspect it's a date formatting issue.
Maybe this question can help you with logging the queries that hit the database:
Hope this helps:
Select * from [Table] where StartDate between '06/13/2016' and '10/13/2016'
The above query fetches records between months 06 and 10. Make sure that string in the data variable is in the above format. Also the column type in the database is date.
Check and remove special characters, if any.
Mark this as answer if you find this useful.
Try this for your select query. I have changed one of your select variable because it ambiguous for the Date datatype.
void FilterDBbtnClick(object sender, EventArgs e)
{
MySqlConnection conn = new MySqlConnection();
conn = new MySqlConnection(cs);
//string data = "SELECT `Date`, `Process`, `Actual`, `Target` FROM `database` WHERE `Date` BETWEEN '"+this.fromDatePicker.Value+"' AND '"+this.toDatePicker.Value+"' order by `Date` desc";
//Changed query for getting data from DB according to the date
string data = "SELECT CreatedDate, Process, Actual, Target FROM database WHERE DATE_FORMAT(CreatedDate,'%Y-%m-%d') BETWEEN '"+this.fromDatePicker.Value.ToString("yyyy-MM-dd")+"' AND '"+this.toDatePicker.Value.ToString("yyyy-MM-dd")+"' order by CreatedDate desc";
MySqlCommand cmd = new MySqlCommand(data, conn);
cmd.Connection.Open();
try
{
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmd;
DataSet dt = new DataSet();
sda.Fill(dt);
BindingSource bsource = new BindingSource();
bsource.DataSource = dt;
mondeDataTable.DataSource = dt.Tables[0];
sda.Update(dt);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
cmd.Connection.Close();
}
[SOLVED]
SOLUTION: When you execute the program inside visual studio it won't commit the changes to the database, but instead, it will work with a copy. When you deploy your program to an executable file, this executable is able to modify permanently your database. Hope this helps anyone :)
As i've said in this question HERE, I can't save the changes of my dataset to my DataBase. I tried to follow this tutorial HERE and couldn't get it to work either: The program compiles and executes, but the new data isn't committed to the DB. Here's the code I wrote following the turorial.
//METHOD INSIDE MY SIGN UP WINDOWS FORM
public static SqlDataAdapter GetuserRecord()
{
SqlConnection connection = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\DatabaseJogo.mdf;Integrated Security=True");
string query = "Select * from dbo.[user]";
SqlCommand command = new SqlCommand(query, connection);
connection.Open();
SqlDataAdapter adp = new SqlDataAdapter(command);
MessageBox.Show("CONNECTION SUCCESFUL");
return adp;
}
//WHEN MY SIGN UP BUTTON IS CLICKED:
SqlDataAdapter adp = GetuserRecord();
DataSet ds = new DataSet();
adp.Fill(ds);
DataRow newRow = ds.Tables[0].NewRow();
newRow["login"] = loginText.Text.Trim();
newRow["name"] = nameText.Text.Trim();
newRow["age"] = int.Parse(ageText.Text.Trim());
newRow["graphicsScore"] = trackBar1.Value;
newRow["storyScore"] = trackBar2.Value;
newRow["gameplayScore"] = trackBar3.Value;
newRow["password"] = passwordText.Text.Trim();
newRow["isAdmin"] = isAdmin.Checked;
newRow["sex"] = sex.Text.Trim();
ds.Tables[0].Rows.Add(newRow);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(adp);
adp.UpdateCommand = commandBuilder.GetUpdateCommand(true);
adp.InsertCommand = commandBuilder.GetInsertCommand(true);
adp.DeleteCommand = commandBuilder.GetDeleteCommand(true);
adp.Update(ds);
EDIT: CHANGED THE CODE TO A NEW ONE, BUT THE PROBLEM IS STILL THE SAME. IF YOU WANT TO TAKE A LOOK, HERE IT IS:
//TRY 3 SQL
//https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqltransaction.commit(v=vs.110).aspx
SqlConnection connection = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\DatabaseJogo.mdf;Integrated Security=True");
connection.Open();
SqlCommand command = connection.CreateCommand();
SqlTransaction transaction;
transaction = connection.BeginTransaction("SIGNUP");
command.Connection = connection;
command.Transaction = transaction;
try
{
command.CommandText = "INSERT INTO [user] ([login], [name], [age], [graphicsScore], [storyScore], [gameplayScore], [password], [isAdmin], [sex]) VALUES (#login, #name, #age, #graphicsScore, #storyScore, #gameplayScore, #password, #isAdmin, #sex);";
command.Parameters.Add("#login", SqlDbType.NChar, 50).Value = loginText.Text.Trim();
command.Parameters.Add("#name", SqlDbType.NChar, 50).Value = nameText.Text.Trim();
command.Parameters.Add("#age", SqlDbType.Int).Value = int.Parse(ageText.Text.Trim());
command.Parameters.Add("#graphicsScore", SqlDbType.Int).Value = trackBar1.Value;
command.Parameters.Add("#storyScore", SqlDbType.Int).Value = trackBar2.Value;
command.Parameters.Add("#gameplayScore", SqlDbType.Int).Value = trackBar3.Value;
command.Parameters.Add("#password", SqlDbType.NChar, 50).Value = passwordText.Text.Trim();
command.Parameters.Add("#isAdmin", SqlDbType.Bit).Value = isAdmin.Checked;
command.Parameters.Add("#sex", SqlDbType.NChar).Value = sex.Text.Trim();
command.ExecuteNonQuery();
transaction.Commit();
MessageBox.Show("COMMITTED");
}
catch (Exception expt)
{
MessageBox.Show(expt.Message);
try
{
transaction.Rollback();
}
catch (Exception ex2)
{
// This catch block will handle any errors that may have occurred
// on the server that would cause the rollback to fail, such as
// a closed connection.
MessageBox.Show("Rollback Exception Type: " + ex2.GetType());
MessageBox.Show(" Message: " + ex2.Message);
}
}
//connection.UpdateDatabase(ds);
connection.Close();
In order to Updateupdate the data on the database your SqlDataAdapter need to have its InsertCommand, UpdateCommand, DeleteCommand properties set.
So, try the below code:
ds.Tables[0].Rows.Add(newRow);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(adp);
adp.DeleteCommand = commandBuilder.GetDeleteCommand(true);
adp.UpdateCommand = commandBuilder.GetUpdateCommand(true);
adp.InsertCommand = commandBuilder.GetInsertCommand(true);
adp.Update(ds.Tables[0]);
//connection.UpdateDatabase(ds);
connection.Close();
Edit:
The Update method takes the name of a DataSet and a table. The DataSet for us is ds, which is the one we passed in to our UpdateDatabase method when we set it up. After a dot, you type the name of a table in your dataset.
I am going thru the same thing:
I can create the dataset, then insert, update and delete, then have the changed dataset's data displayed. This works so far as expected as all the changes of the dataset show. But you can run this again and again, so: the data in the underlying database is not changed.
Either some final commit somewhere is missing or it just does not work as it should and as these methods are not current any more nobody cares.
Sincerly
Andi
I have a Windows Forms Application. I have to search data from the MySQL database using the "Like" operator. I have used the placeholder (#test, see code below) for the search term but it does not happen.
In simple, I have a TestBox named txtSearch in which I can enter the name of a student partially or completely. I need to retrieve all the entries matching search criteria on DataGrid.
Please check my code below and let me know where I am wrong (Conn String is removed below) :
try
{
dataGridView1.Visible = true;
BindingSource bs = new BindingSource();
DataTable newadm = new DataTable();
String term = txtSearch.Text;
string db = ----Connection String goes here----
bs.DataSource = newadm;
this.dataGridView1.DataSource = bs;
MySqlConnection conn = new MySqlConnection(db);
conn.Open();
string s = "select * from newadm where firstname like '%#term%' OR lastname like '%#term%'";
MySqlCommand cmd = new MySqlCommand(s, conn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#term", MySqlDbType.VarChar).Value = txtSearch.Text;
MySqlDataAdapter da = new MySqlDataAdapter();
da.SelectCommand = new MySqlCommand(s, conn);
da.Fill(newadm);
da.Update(newadm);
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
I get no results in DataGrid using this code(and many variations of it). If I remove the "#Term" place holder, and replace the exact terms, it works.
Please help out. Thanks in advance.
Try,
string s = "select * from newadm where firstname like #term OR lastname like #term";
MySqlCommand cmd = new MySqlCommand(s, conn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#term", MySqlDbType.VarChar,40).Value = "%" + txtSearch.Text + "%";