I am trying to build a C#.net program that works like a RPG Subfile on the AS400.
Have the general subfile part working. I can display and then edit and update existing records.
Am blowing up in my code where I am trying to insert a new record. Blowing up on the
cmd.ExecuteNonQuery();
If you want to see how this works without the insert go to
http://144.162.90.78/thomas/
Look at the Website1a
Here is the code.
using IBM.Data.DB2.iSeries;
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class WebForm3 : System.Web.UI.Page
{
protected void btnBack_Click(object sender, EventArgs e)
{
Server.Transfer("WebForm1a.aspx");
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
ConnectionStringSettingsCollection cssc =
ConfigurationManager.ConnectionStrings;
String connString = cssc["FTWAS400"].ToString();
iDB2Connection conn = new iDB2Connection(connString);
conn.Open();
iDB2Command cmd = new iDB2Command(
"insert into tburrows.qcustcdt (cusnum, init, lstnam, street, city, state, zipcod, cdtlmt, chgcod, baldue, cdtdue) values (#cusnum, #init, #lstnam, #street, #city, #state, #zipcod, #cdtlmt, #chgcod, #baldue, #cdtdue)", conn);
cmd.DeriveParameters();
cmd.Parameters["#cusnum"].Value = Request["txtCUSNUM"];
cmd.Parameters["#init" ].Value = Request["txtINIT"];
cmd.Parameters["#lstnam"].Value = Request["txtLSTNAM"];
cmd.Parameters["#street"].Value = Request["txtSTREET"];
cmd.Parameters["#city"].Value = Request["txtCITY"];
cmd.Parameters["#state"].Value = Request["txtSTATE"];
cmd.Parameters["#zipcod"].Value = Request["txtZIPCOD"];
cmd.Parameters["#cdtlmt"].Value = Request["txtCDTLMT"];
cmd.Parameters["#chgcod"].Value = Request["txtCHGCOD"];
cmd.Parameters["#baldue"].Value = Request["txtBALDUE"];
cmd.Parameters["#cdtdue"].Value = Request["txtCDTDUE"];
cmd.ExecuteNonQuery();
cmd.Dispose();
conn.Close();
btnBack_Click(sender, e);
}
}
Any help will greatly be appreciated.
Thomas
There is another option within the
cmd.Parameters["#cusnum"].Value = field;
to specify the field type. Use
cmd.Parameters.Add("#cusnum", iDB2DbType.iDB2Decimal).Value = Convert.ToDecimal(field);
instead. This should convert your data types properly. You will need to change the iDB2Decimal to the proper field type if not decimal.
Related
I am creating a practice SQL Server database project, and I'm trying to enter text into a SQL Server database through a Windows Form. I'm not sure if my text data was really entered to my database. How do I view if it was entered? I'm a beginner so please try to use beginner SQL and VS vocabulary. I've tried going to show table data but that shows that no data was entered so I'm assuming its not working. Whenever I hit the button it just gives me no response so I'm not sure.
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;
using System.Data.SqlClient;
namespace DBHotel
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string connectionString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\Nicholas Hoffs\\source\\repos\\DBHotel\\DBHotel\\Hotel.mdf;Integrated Security=True";
private void instBttn_Click(object sender, EventArgs e)
{
string nameQuery = textInst.Text;
using(SqlConnection conn = new SqlConnection(connectionString))
{
using(SqlCommand cmd = new SqlCommand(nameQuery, conn))
{
conn.Open();
cmd.CommandText = "INSERT INTO Customers(name) VALUES(#nameQuery)";
cmd.Parameters.AddWithValue("nameQuery", nameQuery);
cmd.ExecuteNonQuery();
}
}
}
}
}
Help is very much appreciated, thanks!
I know this is nonintuitive but try using the # inside your AddWithValue:
cmd.Parameters.AddWithValue("#nameQuery", nameQuery);
EDIT: WARNING The below solution is at risk of sql injection, and is highly discouraged.
As you are using direct query in instead of using stored procedure, you can't pass parameter to SQL. Instead of passing parameter try using
cmd.CommandText = "INSERT INTO Customers(name) VALUES('" + nameQuery + "')";
this means we are just concatenating the value of variable "nameQuery" in the query itself. so no need of below statement
cmd.Parameters.AddWithValue("nameQuery", nameQuery);
I am trying to simply insert values into an SQL table. The ID in the database cannot be AUTO_INCREMENT so I use MAX and +1. Not only will this code not make a new ID, it simply isn't inserting anything into the table.
Even in the debugger there are no errors or warnings, it just isn't showing up in the database itself..
Here is my code:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Windows;
using System.ComponentModel;
using System.Drawing;
using System.Text;
namespace WebApplication2
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ButtonClick(object sender, EventArgs e){
using (var sqlConnection1 = new SqlConnection("Data
Source=SERVER; Initial Catalog = Metal; Integrated
Security = True"))
{
SqlDataAdapter cmd = new SqlDataAdapter();
using (var insertData = new SqlCommand("INSERT INTO ApptIn
(CONTROLNUMBER, CARRIERNAME, EXPECTEDNUMOFPIECES, EXPECTEDWEIGHT) VALUES
(#carrierSelectInput,
#pieceCountInput, #weightinput)")
{
SqlCommand generateApptNum = new SqlCommand();
View appNumView = new View();
insertData.Connection = sqlConnection1;
string carrierSelectInput = DropDownList1.Text;
string pieceCountInput = TextBox1.Text;
string weightInput = TextBox2.Text;
insertData.Parameters.Add("#carrierSelectInput",
carrierSelectInput.VarChar);
insertData.Parameters.Add("#pieceCountInput",
pieceCountInput.Int);
insertData.Parameters.Add("#weightInput",
weightInput.Int);
cmd.InsertCommand = insertData;
sqlConnection1.Open();
insertData.ExecuteNonQuery();
generateApptNum.ExecuteNonQuery();
sqlConnection1.Close();
}
}
}
}
}
EDIT: I have tried running the SQL into the DB and it gave an error, so I changed it(updated in code) but it puts in at ID=0...
I know you have already committed to your plan, but, I feel that I have to point out that, due to the sub select for the Max id value in your query, the insert statement has the potential to be much slower than a normal insert.
If you are planning on inserting a large number of rows or creating an API for use throughout the code I highly recommend either adjusting the column definition to be an identity column or to consider using a a sequence to generate the ids.
The issue could be that you need to specify the CommandType to be CommandType.Text on the insertData command. There is a lot going on in the original code with multiple sqlcommands being declared. I think the code could be simplified as such:
protected void ButtonClick(object sender, EventArgs e)
{
using (var sqlConnection1 = new SqlConnection("data source=testServer;initial catalog=testCat;integrated security=True;"))
using (var insertData = new SqlCommand("insert into tempExample (id, code, description) values ((select max(coalesce(id, 1)) from tempExample)+1, #code, #description)", sqlConnection1))
{
insertData.CommandType = CommandType.Text;
insertData.Parameters.AddWithValue("#code", "Testing4");
insertData.Parameters.AddWithValue("#description", "Testing3");
sqlConnection1.Open();
insertData.ExecuteNonQuery();
sqlConnection1.Close();
}
}
Update - I changed the code above to reflect a working test on my local machine. Note that the connection string format is different (lack of spaces).
I am currently developing a website by visual studio c# language and right now I am working on the user password reset page design. The problem I met is that I want to add the control to the textboxes and labels by using basic textbox.text = ""; method. But it keeps telling me it did not exist. I have searched a lot of solutions I am sure that:
1, It is the same name between the label name and the coding name.
2, There were no other same name pages since I was re-created another page with different names.
3, All these are added:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Net.Mail;
using System.Drawing;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Text;
using System.IO;
Can anyone help? I confused here for a few days already:)
protected void SubmitButton_Click(object sender, EventArgs e)
{
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("spResetPassword", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter paramUsername = new SqlParameter("#UserName", userTextBox.text);
cmd.Parameters.Add(paramUsername);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
if (Convert.ToBoolean(rdr["ReaturnCode"]))
{
SendPasswordResetEmail(rdr["Email"].ToString(), TextBox1.Text, rdr["UniqueId"].ToString());
msgLabel.Text = "An reset password Email has sent to your Email address.";
}
else
{
msgLabel.Text = "username not found!";
}
}
}
Does your textbox control have the following attribute?
runat="server"
My first issue: I am trying to establish connection to MySql database, but I keep getting error when I debug it with Visual Studio:"Connection must be valid and open."
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
using MySql.Data.MySqlClient;
using MySql.Data.Types;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
MySqlConnection conn;
string myConnectionString;
myConnectionString = "server=localhost;User Id=root;database=test3";
using (conn = new MySqlConnection(myConnectionString))
{
DateTime startTime = DateTime.Now;
MySqlCommand cmd = new MySqlCommand("SELECT * FROM department");
// sleep for 2.5s
Thread.Sleep(2500);
conn.Open();
var reader = cmd.ExecuteReader();
conn.Close();
}
}
}
My second issue: if there a way to display all this on a ASP.NET Web form (I want to leave code on server side), but display data something like ListView or GridView? Thanks in advance
You need to call conn.Open() before using it.
You forgot to attach your connection to the command:
cmd.Connection = conn;
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 ...