I have a problem with data management in the postgre database. I`m connected, now i want to add any value, but that what i wrote dosent work.
protected void Page_Load(object sender, EventArgs e)
{
try
{
Label1.Text = "Połączenie z bazą danych zakonczońe sukcesem";
NpgsqlConnection conn = new NpgsqlConnection("Server=localhost;Port=5432;Database=dt_PackageWarehouse;User Id=postgres;Password=321qweQAZ");
conn.Open();
NpgsqlCommand comm = new NpgsqlCommand();
comm.Connection = conn;
comm.CommandType = CommandType.Text;
comm.CommandText = "select * from magazynpaczek";
NpgsqlDataAdapter nda = new NpgsqlDataAdapter(comm);
DataTable dt = new DataTable();
nda.Fill(dt);
comm.Dispose();
conn.Close();
GridView1.DataSource = dt;
GridView1.DataBind();
}
catch (Exception)
{
Label1.Text = "Połączenie z bazą danych zakonczońe niepowodzeniem";
}
}
protected void btnDodaj_Click(object sender, EventArgs e)
{
NpgsqlConnection conn = new NpgsqlConnection("Server=localhost;Port=5432;Database=dt_PackageWarehouse;User Id=postgres;Password=321qweQAZ");
string query = "Insert into public.magazynpaczek(id, nazwafirmynadawcy, imienadawcy, nazwiskonadawcy, nrtelefonunadawcy, miastonadawcy, ulicanadawcy, nazwafirmyodbiorcy," +
" imieodbiorcy, nazwiskoodbiorcy, nrtelefonuodbiorcy, miastoodbiorcy, ulicaodbiorcy, nrprzesylki, datadoreczenia) VALUES(#NFN, #txtIN, #txtNN, #txtNTN, #txtMN," +
"#txtUN, #txtNFO, #txtIO, #txtNO, #txtNTO, #txtMO, #txtUO, #txtNP, #txtDD)";
NpgsqlCommand comm = new NpgsqlCommand(query, conn);
conn.Open();
comm.ExecuteNonQuery();
conn.Close();
}
you have to create and add a parameter for each insert value:
var query = "Insert into public.magazynpaczek(id, nazwafirmynadawcy, imienadawcy, nazwiskonadawcy, nrtelefonunadawcy, miastonadawcy, ulicanadawcy, nazwafirmyodbiorcy," +
" imieodbiorcy, nazwiskoodbiorcy, nrtelefonuodbiorcy, miastoodbiorcy, ulicaodbiorcy, nrprzesylki, datadoreczenia) VALUES(#NFN, #txtIN, #txtNN, #txtNTN, #txtMN," +
"#txtUN, #txtNFO, #txtIO, #txtNO, #txtNTO, #txtMO, #txtUO, #txtNP, #txtDD)";
IDbCommand command = conn.CreateCommand();
command.CommandText = query;
var parameter = command.CreateParameter();
parameter.ParameterName = "NFN";
parameter.Value = nfn;
command.Parameters.Add(parameter);
parameter = command.CreateParameter();
parameter.ParameterName = "txtIN";
parameter.Value = txtIN.text;
command.Parameters.Add(parameter);
.... and so on
conn.Open();
command.ExecuteNonQuery();
conn.Close();
I am finding error of No value given for one or required parameter C# update query where ever i try to update my c# access data base here is the code...
hope somebody will be of my assistant..
private void updatebutton_Click(object sender, EventArgs e)
{
try
{
con.Open();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = con;
string query = "update Emplyeedata set [ID]='" + midbox.Text + "',[Name]='" + mnamebox.Text + "',[Deisgnation]='" + mdesbox.Text + "',[Leave]='" + mleavebox.Text + "'Where [Name]='"+mnamebox.Text+"'";
cmd.CommandText = query;
cmd.ExecuteNonQuery();
con.Close();
cb();
MessageBox.Show("Updated", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch
{
MessageBox.Show("Error", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
as a bit more improvement you can try like this, and if you can post the full error information.
private void updatebutton_Click()
{
using (OleDbConnection con = new OleDbConnection("Define your Connection String here"))
{
string query = #"UPDATE Emplyeedata
SET [id] = #ID
,[Name] = #Name
,[Deisgnation] = #Deisgnation
,[Leave] = #Leave
WHERE [Name] = #Name";
using (OleDbCommand cmd = new OleDbCommand(query, con) { CommandType = CommandType.Text })
{
cmd.Parameters.AddWithValue("#ID", midbox.Text);
cmd.Parameters.AddWithValue("#Name", mnamebox.Text);
cmd.Parameters.AddWithValue("#Deisgnation", mdesbox.Text);
cmd.Parameters.AddWithValue("#Leave", mleavebox.Text);
cmd.Parameters.AddWithValue("#Name", mnamebox.Text);
con.Open();
cmd.ExecuteNonQuery();
}
con.Close();
}
}
(this is a really unstructured way and please follow the SOLID Principle/s)
I created a folder on a webform in visual studio for images and titled as (Invoices), I want to save the root of images in MySql database and display the images on a panel one the webpage. The image has been saved on the folder but not on database.
The Codes I have tried
protected void Page_Load(object sender, EventArgs e)
{
string connection = "server=localhost; userid= ; password= ; database=admindb; allowuservariables=True";
MySqlConnection cn = new MySqlConnection(connection);
try
{
string sqlcmd = "SELECT PicAddress FROM InvoicesFP WHERE InvoicesFP_ID=#InvoicesFP_ID";
cn.Open();
MySqlCommand cmd = new MySqlCommand(sqlcmd, cn);
cmd.CommandType = CommandType.Text;
MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
string url = rdr["PicAddress"].ToString();
Image1.ImageUrl = url;
}
}
catch (Exception ex)
{
throw ex;
}
cn.Close();
}
protected void Button1_Click(object sender, EventArgs e)
{
#region fileupload
var FileExtension = Path.GetExtension(FileUpload1.PostedFile.FileName).Substring(1);
string SaveLocation = Server.MapPath("Invoices\\") + Guid.NewGuid().ToString("N") + FileExtension;
MySqlConnection connection = new MySqlConnection("server=localhost; userid=root; password=admin1234; database=admindb; allowuservariables=True");
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = "insert into invoicesfp (PicAddress), VALUES (#PicAddress)";
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("PicAddress", Server.MapPath("~/Invoices"));
cmd.Connection.Open();
cmd.BeginExecuteNonQuery();
cmd.Connection.Close();
try
{
FileUpload1.PostedFile.SaveAs(SaveLocation);
}
catch (Exception ex)
{
if (ex is ArgumentNullException || ex is NullReferenceException)
{
throw ex;
}
}
string PicAddress = "~/Invoices/" + SaveLocation;
}
#endregion
}
Update
Try this Code first, using this sample you do not need to use Rename Method And whatever its Extension is, it is supported:
#region fileupload
var FileExtension = Path.GetExtension(FileUpload1.PostedFile.FileName).Substring(1);
string SaveLocation = Server.MapPath("Invoices\\") + Guid.NewGuid().ToString("N") + "." + FileExtension;
try
{
FileUpload1.PostedFile.SaveAs(SaveLocation);
}
catch (Exception ex)
{
if (ex is ArgumentNullException || ex is NullReferenceException)
{
throw ex;
}
}
string PicAddress = "~/Invoices/" + SaveLocation;
#endregion
MySqlConnection connection = new MySqlConnection("server=localhost; userid=root; password=admin1234; database=admindb; allowuservariables=True");
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = "INSERT INTO InvoicesFP (PicAddress) VALUES (#PicAddress)";
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("PicAddress", "PicAddress");
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
then in your page_load you can call the Select Query to get the Address out database and pass it over to control e.g:
const string DB_CONN_STR = "Server=etc;Uid=etc;Pwd=etc;Database=etc;";
MySqlConnection cn = new MySqlConnection(DB_CONN_STR);
try {
string sqlCmd = "SELECT PicAddress FROM [YourTable] where Id == PicAddress id";
cn.Open(); // have to explicitly open connection (fetches from pool)
MySqlCommand cmd = new MySqlCommand(sqlCmd, cn);
cmd.CommandType = CommandType.Text;
MySqlDataReader rdr = cmd.ExecuteReader();
while(rdr.Read())
{
string url = rdr["Name of the Field Assuming PicAddress"].ToString();
Image1.ImageUrl = url;
}
}
catch(Exception ex)
{
throw ex;
}
Thats All - Happy Coding
private void bLogIn(object sender, EventArgs e)
{
string logging = "select * from CLIENT where LOGIN='" + this.t_Login.Text + "' and PASSWORD='" + this.t_Password.Text + "' ;";
OracleConnection conn = new OracleConnection("Data Source=XXX/orcl;User Id=XXX;Password=XXX;");
OracleCommand cmd = new OracleCommand();
cmd.CommandText = logging;
cmd.Connection = conn;
try
{
conn.Open();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
int count = 0;
OracleDataReader reader = cmd.ExecuteReader(); // At this line there is the error: Operation is not valid due to the current state of the object
while (reader.Read())
{
count = count + 1;
}
if (count == 1)
{
MessageBox.Show("Welcome");
}
else
{
MessageBox.Show("Wrong Password");
}
conn.Dispose();
}
This is code that was working for MySQL, but after conversion to Oracle it's not working. What am I doing wrong? Where's the difference. It should be so easy as in MySQL, right?
Why "OracleDataReader reader = cmd.ExecuteReader();" causes error: "Operation is not valid due to the current state of the object" ???
You are not assingning the connection to cmd.. try code below
OracleCommand cmd = new OracleCommand();
cmd.connection = conn;
cmd.CommandText = logging;
int count = 0;
OracleDataReader reader = cmd.ExecuteReader();
I'm having an issue at the moment which I am trying to fix. I just tried to access a database and insert some values with the help of C#
The things I tried (worked)
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES ('abc', 'abc', 'abc', 'abc')";
A new line was inserted and everything worked fine, now I tried to insert a row using variables:
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (#id, #username, #password, #email)";
command.Parameters.AddWithValue("#id","abc")
command.Parameters.AddWithValue("#username","abc")
command.Parameters.AddWithValue("#password","abc")
command.Parameters.AddWithValue("#email","abc")
command.ExecuteNonQuery();
Didn't work, no values were inserted. I tried one more thing
command.Parameters.AddWithValue("#id", SqlDbType.NChar);
command.Parameters["#id"].Value = "abc";
command.Parameters.AddWithValue("#username", SqlDbType.NChar);
command.Parameters["#username"].Value = "abc";
command.Parameters.AddWithValue("#password", SqlDbType.NChar);
command.Parameters["#password"].Value = "abc";
command.Parameters.AddWithValue("#email", SqlDbType.NChar);
command.Parameters["#email"].Value = "abc";
command.ExecuteNonQuery();
May anyone tell me what I am doing wrong?
Kind regards
EDIT:
in one other line I was creating a new SQL-Command
var cmd = new SqlCommand(query, connection);
Still not working and I can't find anything wrong in the code above.
I assume you have a connection to your database and you can not do the insert parameters using c #.
You are not adding the parameters in your query. It should look like:
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (#id,#username,#password, #email)";
SqlCommand command = new SqlCommand(query, db.Connection);
command.Parameters.Add("#id","abc");
command.Parameters.Add("#username","abc");
command.Parameters.Add("#password","abc");
command.Parameters.Add("#email","abc");
command.ExecuteNonQuery();
Updated:
using(SqlConnection connection = new SqlConnection(_connectionString))
{
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (#id,#username,#password, #email)";
using(SqlCommand command = new SqlCommand(query, connection))
{
command.Parameters.AddWithValue("#id", "abc");
command.Parameters.AddWithValue("#username", "abc");
command.Parameters.AddWithValue("#password", "abc");
command.Parameters.AddWithValue("#email", "abc");
connection.Open();
int result = command.ExecuteNonQuery();
// Check Error
if(result < 0)
Console.WriteLine("Error inserting data into Database!");
}
}
Try
String query = "INSERT INTO dbo.SMS_PW (id,username,password,email) VALUES (#id,#username, #password, #email)";
using(SqlConnection connection = new SqlConnection(connectionString))
using(SqlCommand command = new SqlCommand(query, connection))
{
//a shorter syntax to adding parameters
command.Parameters.Add("#id", SqlDbType.NChar).Value = "abc";
command.Parameters.Add("#username", SqlDbType.NChar).Value = "abc";
//a longer syntax for adding parameters
command.Parameters.Add("#password", SqlDbType.NChar).Value = "abc";
command.Parameters.Add("#email", SqlDbType.NChar).Value = "abc";
//make sure you open and close(after executing) the connection
connection.Open();
command.ExecuteNonQuery();
}
The most common mistake (especially when using express) to the "my insert didn't happen" is : looking in the wrong file.
If you are using file-based express (rather than strongly attached), then the file in your project folder (say, c:\dev\myproject\mydb.mbd) is not the file that is used in your program. When you build, that file is copied - for example to c:\dev\myproject\bin\debug\mydb.mbd; your program executes in the context of c:\dev\myproject\bin\debug\, and so it is here that you need to look to see if the edit actually happened. To check for sure: query for the data inside the application (after inserting it).
static SqlConnection myConnection;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
myConnection = new SqlConnection("server=localhost;" +
"Trusted_Connection=true;" +
"database=zxc; " +
"connection timeout=30");
try
{
myConnection.Open();
label1.Text = "connect successful";
}
catch (SqlException ex)
{
label1.Text = "connect fail";
MessageBox.Show(ex.Message);
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
String st = "INSERT INTO supplier(supplier_id, supplier_name)VALUES(" + textBox1.Text + ", " + textBox2.Text + ")";
SqlCommand sqlcom = new SqlCommand(st, myConnection);
try
{
sqlcom.ExecuteNonQuery();
MessageBox.Show("insert successful");
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
private void button1_Click(object sender, EventArgs e)
{
String query = "INSERT INTO product (productid, productname,productdesc,productqty) VALUES (#txtitemid,#txtitemname,#txtitemdesc,#txtitemqty)";
try
{
using (SqlCommand command = new SqlCommand(query, con))
{
command.Parameters.AddWithValue("#txtitemid", txtitemid.Text);
command.Parameters.AddWithValue("#txtitemname", txtitemname.Text);
command.Parameters.AddWithValue("#txtitemdesc", txtitemdesc.Text);
command.Parameters.AddWithValue("#txtitemqty", txtitemqty.Text);
con.Open();
int result = command.ExecuteNonQuery();
// Check Error
if (result < 0)
MessageBox.Show("Error");
MessageBox.Show("Record...!", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
con.Close();
loader();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
con.Close();
}
}
public static string textDataSource = "Data Source=localhost;Initial
Catalog=TEST_C;User ID=sa;Password=P#ssw0rd";
public static bool ExtSql(string sql) {
SqlConnection cnn;
SqlCommand cmd;
cnn = new SqlConnection(textDataSource);
cmd = new SqlCommand(sql, cnn);
try {
cnn.Open();
cmd.ExecuteNonQuery();
cnn.Close();
return true;
}
catch (Exception) {
return false;
}
finally {
cmd.Dispose();
cnn = null;
cmd = null;
}
}
I have just wrote a reusable method for that, there is no answer here with reusable method so why not to share...here is the code from my current project:
public static int ParametersCommand(string query,List<SqlParameter> parameters)
{
SqlConnection connection = new SqlConnection(ConnectionString);
try
{
using (SqlCommand cmd = new SqlCommand(query, connection))
{ // for cases where no parameters needed
if (parameters != null)
{
cmd.Parameters.AddRange(parameters.ToArray());
}
connection.Open();
int result = cmd.ExecuteNonQuery();
return result;
}
}
catch (Exception ex)
{
AddEventToEventLogTable("ERROR in DAL.DataBase.ParametersCommand() method: " + ex.Message, 1);
return 0;
throw;
}
finally
{
CloseConnection(ref connection);
}
}
private static void CloseConnection(ref SqlConnection conn)
{
if (conn.State != ConnectionState.Closed)
{
conn.Close();
conn.Dispose();
}
}
class Program
{
static void Main(string[] args)
{
string connetionString = null;
SqlConnection connection;
SqlCommand command;
string sql = null;
connetionString = "Data Source=Server Name;Initial Catalog=DataBaseName;User ID=UserID;Password=Password";
sql = "INSERT INTO LoanRequest(idLoanRequest,RequestDate,Pickupdate,ReturnDate,EventDescription,LocationOfEvent,ApprovalComments,Quantity,Approved,EquipmentAvailable,ModifyRequest,Equipment,Requester)VALUES('5','2016-1-1','2016-2-2','2016-3-3','DescP','Loca1','Appcoment','2','true','true','true','4','5')";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
Console.WriteLine(" Connection Opened ");
command = new SqlCommand(sql, connection);
SqlDataReader dr1 = command.ExecuteReader();
connection.Close();
}
catch (Exception ex)
{
Console.WriteLine("Can not open connection ! ");
}
}
}