C# connection issue - c#

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;

Related

SQL Server exception 'Must declare the scalar variable "#nameQuery".'

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);

Visual C# SQL statement won't insert into database

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).

Adding Data to Database but get a breakpoint everytime a function is called

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.

Update DB using stored procedure and ADO.NET

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 ...

AS400 C#.net inserting new record problems

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.

Categories