Book_Return_form
Book_tag_id=textbox1
Member_id=textbox2
Book_return_on=textbox3
Book_due_date=textbox4
Fine=textbox5
In this form when I put book-tag_id the rest items come automatically a/c to database and I hv done all till textbox4(book_due_date).
Now problem is with fine(textbox5)
Fine is calculated acc to membership_type,there are three types of membership silver,gold,platinum
Fines are:silver=30,gold=20,platinum=30 so the calculated fine a/c membership come on text box
As (return_date-due_date)-30,20or10 ,till now I m working with dataadapter but now I want to work with dll class,I make a dll class and know how to add reference to project but I m missing smthing in my code while I m making class.(so help me in code)
I made a stored procedure with name(member_details)colums:tag_id,member_id,membership_type_id,membership_type(eg:909,5,1,silver)
My full code for dll class is:
Firstly,I make class name transcation_details
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace selectfinedetails
{
public class TransactionService
{
SqlConnection cs;
private void OpenConnection()
{
cs = new SqlConnection();
cs.ConnectionString = "Data Source=IRIS-CSG-174;Initial Catalog=library_system;Integrated Security=True";
cs.Open();
}
public membership_details calculatefine()
{
OpenConnection();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "Exec member_fine_detail";
SqlParameter prm1=new SqlParameter("member_id", SqlDbType.Int);
cmd.Parameters.Add(prm1);
SqlParameter prm2=new SqlParameter("fine_per_day", SqlDbType.Int);
cmd.Parameters.Add(prm2);
prm1.Direction=ParameterDirection.Output;
prm2.Direction=ParameterDirection.ReturnValue;
membership_details myObjec = new membership_details();
cmd.ExecuteNonQuery();
SqlDataReader sdr = cmd.ExecuteReader();
myObjec.fine_per_day = //cmd.CommandText;(this is error)
return myObjec;
but I this above code I m missing smthing,as this code will result nthing as to calculate fine with member_id…so what code I will add in it and in as calculatefine()
Related
I wrote code to insert data into the database, after I click the insert button, nothing happens and there is no error. Please I need help.
If I click the insert button from the front end, it is supposed to populate the database.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
namespace insertAdo
{
public partial class TableInsert : System.Web.UI.Page
{
protected void Button1_Click(object sender, EventArgs e)
{
string connectionString;
SqlConnection cnn;
connectionString = #"Data Source=DESKTOP-5JPBK1L;Database=StudentDB; Integrated Security=SSPI";
cnn = new SqlConnection(connectionString);
cnn.Open();
{
SqlCommand command;
SqlDataAdapter adapter = new SqlDataAdapter();
String sql = "";
sql = "INSERT INTO student_table (Student_id, name, Email, Join_date) VALUES (102, 'Jaja Peter', 'Jaja.Peter#gmail.com', '09/30/2021')";
command = new SqlCommand(sql, cnn);
adapter.InsertCommand = new SqlCommand(sql, cnn);
adapter.InsertCommand.ExecuteNonQuery();
command.Dispose();
}
Response.Write("Insert successful");
cnn.Close();
}
}
}
First ensure that your front-end UI button's Click event is wired up , like below in your aspx page.
<asp:Button id="Button1"
Text="Click here for inserting..."
OnClick="Button1_Click"
runat="server"/>
After that make the modification in your .cs code file as below.
string connectionString = #"Data Source=DESKTOP-5JPBK1L;Database=StudentDB; Integrated Security=SSPI";
string sql = "Insert into student_table(Student_id,name,Email,Join_date) values(102,'Jaja Peter','Jaja.Peter#gmail.com','09/30/2021')";
// create connection and command
using(SqlConnection cn = new SqlConnection(connectionString))
using(SqlCommand cmd = new SqlCommand(sql, cn))
{
// open connection, execute INSERT, close connection
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
Use of the using block ensures that your connection and command objects are disposed properly.
For learning, this way of hard coding the values is okay, but in real world scenario, you would need to use parameters, and use model class, not have the connecting string inside your code etc.
I am trying to write myself a Music record database program.
It works perfectly untill I try using a form to add data using input from textboxes and a button.
It generates a break point and the following error
An Unhandled exception of type 'System.ArgumentException' Occured in
System.Data.dll
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace Musicrecord
{
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
--> using(var connection = new SqlConnection("connectionString"))**
{
connection.Open();
var sql = "INSERT INTO Table(Artist, Album, Release Year) VALUES(#Artist, #Album, #Release year)";
using(var cmd = new SqlCommand(sql, connection))
{
cmd.Parameters.AddWithValue("#Artist", textBox1.Text);
cmd.Parameters.AddWithValue("#Album", textBox2.Text);
cmd.Parameters.AddWithValue("#Release Year ", textBox3.Text);
cmd.ExecuteNonQuery();
}
I haven't found after several hours of googling a solution.
If connectionString is a local variable, you need to use it as;
using(var connection = new SqlConnection(connectionString))
not
using(var connection = new SqlConnection("connectionString"))
If you use it as "connectionString", SqlConnection expects it is a valid connection string. But it is not.
Also, if your column name more than one word, you need to use it with square brackets like [Release Year]. It is the same as it's paramter name.
And don't use AddWithValue. It may generate unexpected results. Use .Add() method or it's overloads.
using(var connection = new SqlConnection(connectionString))
using(var cmd = connection.CreateCommand())
{
cmd.CommandText = "INSERT INTO Table(Artist, Album, [Release Year]) VALUES(#Artist, #Album, #ReleaseYear)";
cmd.Parameters.Add(#Artist, SqlDbType.NVarChar).Value = textBox1.Text;
cmd.Parameters.Add(#Album, SqlDbType.NVarChar).Value = textBox2.Text;
cmd.Parameters.Add(#ReleaseYear, SqlDbType.NVarChar).Value = textBox3.Text;
connection.Open();
cmd.ExecuteNonQuery();
}
I assumed your all data types are NVarChar. Also it is a good practice to specify size value as a third parameter in .Add() method.
What is wrong with my code? When Im setting up the connection between my sql and asp, it gives me this error : the sqlcommand cannot be found. Are you missing...."
Here is my code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.Sql;
protected void Button2_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
SqlCommand cmd = new SqlCommand("Insert into CarTab( Brand,Model,Plate,Color,Service) Values (#brand,#model,#plate,#color,#year,#service)",conn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#brand", Label1.Text);
cmd.Parameters.AddWithValue("#model", Label2.Text);
cmd.Parameters.AddWithValue("#plate", Label3.Text);
cmd.Parameters.AddWithValue("#color", Label4.Text);
cmd.Parameters.AddWithValue("#year", Label5.Text);
cmd.Parameters.AddWithValue("#service", Label6.Text);
conn.Open();
cmd.ExecuteNonQuery();
}
I've already put Using system.data; and Using system.data.sql; but it still the same.
Error :
1.The type or namespace name 'SqlConnection' could not be found (are you missing a using directive or an assembly reference?)
2.The type or namespace name 'SqlConnection' could not be found (are you missing a using directive or an assembly reference?)
3.The name 'ConfigurationManager' does not exist in the current context
4.The type or namespace name 'SqlCommand' could not be found (are you missing a using directive or an assembly reference?)
5.The type or namespace name 'SqlCommand' could not be found (are you missing a using directive or an assembly reference?)
Hope this help you in finding solution for my errors. Thanks
Two things. You haven't closed your SQL command:
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
SqlCommand cmd = new SqlCommand("Insert into CarTab")
And secondly, you don't have any qualifying data to insert in to your CarTab table? You need to specify the fields and values:
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
SqlCommand cmd = new SqlCommand("Insert into CarTab(field1, field2) VALUES('val1', 12)")
There are a number of other ways to insert data - like the INSERT SELECT:
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
SqlCommand cmd = new SqlCommand("Insert into CarTab(field1, field2) SELECT field1, field2 FROM Table2")
http://www.sqlteam.com/article/using-select-to-insert-records
Further to the comments, here is an example of how to fully use ADO in the way you have specified:
using System.Data;
using System.Data.SqlClient;
using (var con = new SqlConnection("your connection string")) {
con.Open();
using (var com = con.CreateCommand()) {
var var1 = "test";
var var2 = "test2";
com.CommandText = string.Format("INSERT INTO Table1(col1, col2) VALUES({0}, {1})", var1, var2);
com.CommandType = CommandType.Text;
com.ExecuteNonQuery();
}
con.Close();
}
Please note that I haven't tested it, but it should give you a good starting block.
Have you added reference to System.Data assembly?
1) You have not closed the SqlCommand object and wrong Sql Insert statement.
It would be
SqlCommand cmd = new SqlCommand("Insert into CarTab(col1,col2,...) VALUES(val1,val2,..)");
2) You have not open the connection and not assign a connection to a command object like
conn.Open();
cmd.Connection = conn;
3) and after executing the query you have to close the connection
cmd.ExecuteNonQuery();
conn.Close(); // close the connection.
System.Data.Sql is for SqlServer
http://msdn.microsoft.com/en-us/library/system.data.sql.aspx
The System.Data.Sql namespace contains classes that support SQL
Server-specific functionality.
Use the ADO.NET driver found here: http://www.mysql.com/products/connector/
or use ODBC (not the preferred option).
what kind of db program are you using? since like grayfox said here above you are in need of sql server, and try doing it this way, worked fo rme:
using (SqlConnection connection = new SqlConnection())
{
string connectionStringName = this.DataWorkspace.dbsMSccData.Details.Name;
connection.ConnectionString =
ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
string procedure = entity.Procedure;
using (SqlCommand command = new SqlCommand(procedure, connection))
{
command.CommandType = CommandType.StoredProcedure;
//foreach (var item in entity.StoredProcedureParameters)
//{
// command.Parameters.Add(
// new SqlParameter(item.ParameterName, item.ParameterValue));
//}
connection.Open();
command.ExecuteNonQuery();
}
}
this.Details.DiscardChanges();
I think I'm missing an 'USING" statement in my class as I'm getting an error when I try to set the commandType to stored procedure. When I type 'cmd.CommandType =', Intellisense fails to find the 'CommandType.StoredProcedure (Note: the function is only partly roughed out). Thanks in advance!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
namespace LegacyForms.Personal
{
public partial class FormBuilder : System.Web.UI.Page
{
protected void btnSubmit_Click(object sender, EventArgs e)
{
//Get the DB connection:
string ConnString = ConfigurationManager.AppSettings["AssociatedBank2011ConnectionString"];
SqlConnection conn = new SqlConnection(ConnString);
SqlCommand cmd = new SqlCommand("uspInsertPersonalAccountApplcation", conn);
cmd.Commandtype = **get error here!**
cmd.Parameters.AddWithValue("#AccountType", AcctType);
cmd.Parameters.AddWithValue("#AccountSubType", AcctSubType);
cmd.Parameters.AddWithValue("#CheckingOption", CheckOption);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
}
using System.Data;
You need to reference System.Data. See the MSDN Reference for the CommandType Enumeration. Direct quote:
Namespace: System.Data
Assembly: System.Data (in System.Data.dll)
I'd also recommend the other using statement for your SqlConnection and SqlCommand objects. Since they both implement the IDisposable interface, you can do the following:
string ConnString = ConfigurationManager.AppSettings["AssociatedBank2011ConnectionString"];
using (SqlConnection conn = new SqlConnection(ConnString))
using (SqlCommand cmd = new SqlCommand("uspInsertPersonalAccountApplcation", conn))
{
cmd.Commandtype = CommandType.StoreProcedure;
cmd.Parameters.AddWithValue("#AccountType", AcctType);
cmd.Parameters.AddWithValue("#AccountSubType", AcctSubType);
cmd.Parameters.AddWithValue("#CheckingOption", CheckOption);
conn.Open();
cmd.ExecuteNonQuery();
}
That way, in the case that your code works correctly or throws an exception in the using block, your SqlConnection and SqlCommand will clean up after themselves.
In such situations you can press CTRL + . (ctrl + dot) to get a suggestion like do you want to add using System.Data...
P.S. Teach a men to fish ...
Guys I searched around like hell but nothing could help me so I think it's time to ask. Before I write to problem, I need to say that I need it's solution asap because it's a project that I have to give tomorrow and I stuck on the same subject since ages and still losing time.
OK here it is;
I need to add a book to a library system, at first phase I add the standard book features which has only "one value" like (name, page number, publishing time, publisherID etc) but as wanted by me book MAY HAVE MULTIPLE WRITERS AND CATEGORIES which killed me and still I can't resolve. I tried to add book to it's (books) table then with the information i got from that i did an other insert op. to (bookWriters) table. While I check it, compiler does everything in order without error but when I check table from SQL Server there is nothing.
Here is what I tried to do;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.SqlClient;
namespace Project_
{
public partial class addBook: Form
{
public addBook()
{
InitializeComponent();
}
public main refForm;
int chosenWritersNumber; //how many writers have selected on listbox
int[] writers= { }; // an array list that i keep writerIDs that comes from class
int ind = 0;
int insertedBookID; // to catch latest added book's ID
int chosenWriterID; // writer that will be added
private void bookAddingPreps()
{
chosenWritersNumber = lstWriters.SelectedItems.Count;
Array.Resize<int>(ref writers, chosenWritersNumber );
for (int i = 0; i < chosenWritersNumber ; i++)
{
writers[i] = ((X_Writers)lstWriters.SelectedItems[i]).XWriterID;
}
}
private void addMainBookInfos()
{
SqlConnection con = new SqlConnection(Conn.Activated);
SqlCommand com = new SqlCommand("AddBook", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#BookISBN", txtISBN.Text);
con.Close();
}
private void catchAddedBookID()
{
SqlConnection con = new SqlConnection(Conn.Activated);
SqlCommand com = new SqlCommand("catchBookID", con);
com.CommandType = CommandType.StoredProcedure;
con.Open();
SqlDataReader dr = com.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
insertedBookID = dr.GetInt32(0);
}
}
dr.Close();
con.Close();
}
private void addWritersOfTheBook()
{
chosenWriterID = writers[ind];
SqlConnection con = new SqlConnection(Conn.Activated);
SqlCommand com = new SqlCommand("addBookWriters", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#BookID", insertedBookID);
com.Parameters.AddWithValue("#WriterID", chosenWriterID);
con.Close();
}
I call these methods on click of a button. You see also stored procedure names but as I checked they all correct, there must be a mistake in this page that I still cant see but if it's needed I can add what procedures writes but they all tested and seems working.
So as i said, when i do this, as ind = 0, a writer should have been added, break point shows everything is ok and compiler doesnt show any errors but when I check sql server table, its empty.
Written in C# with using Visual Studio 2010 Ultimate and SQL Server 2008 Dev.
Thanks
You forget to execute your SqlCommand's. Make a call to command.ExecuteNonReader(); to execute it without expecting any results. see: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.aspx
Apart form that, dont forget to dispose the resources acquired in your methods. Something like:
private void addMainBookInfos()
{
using (SqlConnection con = new SqlConnection(Conn.Activated))
using (SqlCommand com = new SqlCommand("AddBook", con))
{
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#BookISBN", txtISBN.Text);
com.ExecuteNonQuery()
// close can be omitted since you are already using the 'using' statement which automatically closes the connection
con.Close();
}
}