i am encountering an error when trying to set up an insert command into my database, it appears to be with the connection string. I am extremely new to all this and am trying to get the correct code in order to upload into my database and assume that the syntax i am using may be wrong and the cause of the error.
Here is the code a little bit clearer:
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 ComputingProjectwh.TestPages._1._Further_Mechanics
{
public partial class Moments_and_Energy_Test1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Submit_Click(object sender, EventArgs e)
{
if (!this.IsValid)
return;
int score = 0;
List<RadioButtonList> list = new List<RadioButtonList>() { RadioButtonList1, RadioButtonList2, RadioButtonList3, RadioButtonList4, RadioButtonList5, RadioButtonList6, RadioButtonList7, RadioButtonList8, RadioButtonList9, RadioButtonList10 };
foreach (var element in list)
{
if (element.SelectedValue == "Correct")
{
score++;
}
}
Response.Write("you scored: " + score);
Button1.Visible = false;
if (score != 0);
{
SqlConnection sqlConnection1 = new SqlConnection (#"Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-ComputingProjectwh-20170404101246.mdf;InitialCatalog=aspnet-ComputingProjectwh-20170404101246;IntegratedSecurity=True");
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT AspNetUserTestScores (Id, MomentAndEnergyTestScore) VALUES (Id, score)";
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
}
}
}
}
I am really not sure what the problem is and cant seem to find an answer on the internet. Any help would be greatly appreciated.
When connecting to MSSQL, there is no initialcatalog, You are using a wrong connection string.
This is the correct syntax:
Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;
Or in your case, for trusted connection:
Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;
With your data:
SqlConnection sqlConnection1 = new SqlConnection("Server=LocalDb;Database=aspnet-ComputingProjectwh-20170404101246.mdf;Trusted_Connection=True;");
InitialCatalog is two separate words initial catalog.
Related
I am trying to connect a MySQL database to a winform using C#. I am receiving this error: System.ArgumentException: 'Keyword not supported: 'host'. I have already checked that the database has a proper connection using the test connection and the connection string that I am using is the one provided to me using the server explorer. After doing research, the issue lies in either the references I'm using or in the app.config itself. Does anyone have any experience with this issue or can offer any feedback? Here is the very basic code snippet i'm working with:
using System;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace savetodatabasepractice
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection())
{
conn.ConnectionString = "User Id=XXXXXX;Host=localhost;Database=XXXXXX";
SqlCommand insertCommand = new SqlCommand("INSERT INTO tbl_newdata (ID, Temperature, Humidity) VALUES (1, 72, 34)", conn);
}
}
}
}
I am using Visual Studio 2017, DotConnect for MySQL, MySQL server, and Wamp Connect. Thank you!
EDIT: After reading documentation a sample c# program with this format should look like
using System;
using System.Windows.Forms;
using Devart.Data.MySql;
namespace savetodatabasepractice
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
MySqlConnection conn = new MySqlConnection("User Id=root;Host=localhost;Database=XXXXXX;");
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = "INSERT INTO tbl_newdata (ID, Temperature, Humidity) VALUES (1,73,32)";
cmd.Connection = conn;
conn.Open();
try
{
int aff = cmd.ExecuteNonQuery();
MessageBox.Show(aff + " rows were affected.");
}
catch
{
MessageBox.Show("Error encountered during INSERT operation.");
}
finally
{
conn.Close();
}
}
}
}
The key is to not only use the correct reference but to also download the correct package on nuget. Easy to forget for beginners!
What??? you are using DotConnect for MySQL but you use a SqlConnection class. That's the issue here cause SqlConnection is for SQLServer. You should use using Devart.Data.MySql.MySqlConnection instead.
using (SqlConnection conn = new SqlConnection())
{
Check the documentation first which says everything. https://www.devart.com/dotconnect/mysql/docs/
I've just started learning C# using Visual Studio 2015, and my task is to create a lottery program that saves the generated numbers into a database. I've tried various methods and none of them seem to make any additions to my table. Can anyone help me understand what I need to do take an Integer that has been generated and converted into a string/ textbox and then insert that value into my table.
Heres my current code below, button 2 being the button I am trying to use to save the data from the textboxes with.
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.Configuration;
using System.Data.SqlClient;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
//Database details
string connectionString;
SqlConnection connection;
public Form1()
{
InitializeComponent();
connectionString = ConfigurationManager.ConnectionStrings["WindowsFormsApplication2.Properties.Settings.LottoConnectionString"].ConnectionString;
}
private void button1_Click(object sender, EventArgs e)
{
Random rnd = new Random();
int[] slot = new int[6];
int counter = 0;
for (int i = 0; i < slot.Length; i++)
{
slot[i] = rnd.Next(0, 100);
}
//Converting generated ints to Strings for display
textBox1.Text = (slot[0].ToString());
textBox2.Text = (slot[1].ToString());
textBox3.Text = (slot[2].ToString());
textBox4.Text = (slot[3].ToString());
textBox5.Text = (slot[4].ToString());
textBox6.Text = (slot[5].ToString());
//Incrementing Counter checks matches
if (numericUpDown1.Value == slot[0])
{
counter += 1;
}
if (numericUpDown2.Value == slot[1])
{
counter += 1;
}
if (numericUpDown3.Value == slot[2])
{
counter += 1;
}
if (numericUpDown4.Value == slot[3])
{
counter += 1;
}
if (numericUpDown5.Value == slot[4])
{
counter += 1;
}
if (numericUpDown6.Value == slot[5])
{
counter += 1;
}
//display total matches
textBox7.Text = ("You got" + counter + "/6 matches!");
LottoDataSetTableAdapters.ResultsTableAdapter resultsTableAdapter =
new LottoDataSetTableAdapters.ResultsTableAdapter();
resultsTableAdapter.Insert((slot[0].ToString()), (slot[1].ToString()), (slot[2].ToString()), (slot[3].ToString()), (slot[4].ToString()), (slot[5].ToString()));
}
private void button2_Click(object sender, EventArgs e)
{
// Adding Data to Database
string query = "INSERT INTO Results VALUES (#First)";
using (connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(query, connection))
{
connection.Open();
command.Parameters.AddWithValue("#First", textBox1.Text);
command.Parameters.AddWithValue("#Second", textBox2.Text);
command.Parameters.AddWithValue("#Third", textBox3.Text);
command.Parameters.AddWithValue("#Fourth", textBox4.Text);
command.Parameters.AddWithValue("#Fifth", textBox5.Text);
command.Parameters.AddWithValue("#Sixth", textBox6.Text);
}
}
}
}
All help will be greatly appreciated.
Your INSERT statement is missing the other parameters in the VALUES portion. You also need to execute the command and you were missing brackets for the using of the connection.
private void button2_Click(object sender, EventArgs e)
{
// Adding Data to Database
string query = "INSERT INTO Results (First, Second, Third, Fourth, Fifth, Sixth) VALUES (#First, #Second, #Third, #Fourth, #Fifth, #Sixth)";
using (var connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand(query, connection))
{
connection.Open();
command.Parameters.AddWithValue("#First", textBox1.Text);
command.Parameters.AddWithValue("#Second", textBox2.Text);
command.Parameters.AddWithValue("#Third", textBox3.Text);
command.Parameters.AddWithValue("#Fourth", textBox4.Text);
command.Parameters.AddWithValue("#Fifth", textBox5.Text);
command.Parameters.AddWithValue("#Sixth", textBox6.Text);
command.ExecuteNonQuery();
}
}
}
It looks like this question as been asked and answered before - have a look here - How to insert data into SQL Server
edit - my first impression was wrong, I can't see where you are executing your query against the db. its been a while since it have written ado code manual without using an orm so forgive me if i am wrong.
I have values from controls txtUser and txtAppNum on a page webform1.aspx. I am bringing those values to a page, Login.aspx. The code from Login.aspx is below. In the login.aspx page, I want to take the values from the controls txtUserand txtAppNum in webform1.aspx page, I want to check the values against a database, if the values are in the database, I want the page to redirect back to webform1.aspx.
My questions is, when I run the code, only Page_Load but not CheckRecord. Basically when I run the page, I can see the values carried over from the webform1.aspx page to login.aspx, but then that's it, nothing else happens.
What am I doing wrong? Any thoughts, I would greatly appreciate it, I have been stuck on this for a few days. Thanks!
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; //to communicate with the Server database
using System.Configuration;
using System.Data; //to use DataSet or DataTable
using System.Text; //for StringBuilder
namespace BLAA_3
{
public partial class login : System.Web.UI.Page
{
public void Page_Load(object sender, EventArgs e)
{
Page PreviousPage = Page.PreviousPage;
if (PreviousPage != null)
{
lblUserLogin.Text = ((TextBox)PreviousPage.FindControl("txtUser")).Text;
lblAppLogin.Text = ((TextBox)PreviousPage.FindControl("txtAppNum")).Text;
}
{
string _connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
}
}
public void CheckRecord(object sender, EventArgs e)
{
//get the connection
using (SqlConnection conn = new SqlConnection(#"Data Source=ServerInfo"))
{
//write the sql statement to execute
string sql = "select username FROM BLAA_users WHERE username = #username";
//instantiate the command object to fire
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
//attatch the parameter to pass, if no parameter is in the sql no need to attatch
SqlParameter[] prms = new SqlParameter[1];
prms[0] = new SqlParameter("#username", SqlDbType.VarChar, 50);
prms[0].Value = lblUserLogin.Text.Trim();
cmd.Parameters.AddRange(prms);
conn.Open();
object obj = cmd.ExecuteScalar();
conn.Close();
if (obj != null)
{
Response.Redirect("~/WebForm1.aspx");
}
else
Response.Redirect("http://www.google.com");
}
}
}
}
}
Is CheckRecord an event handler? If not, you don't need the sender and eventArgs in your signature for CheckRecord it can be public void CheckRecord().
It's not being called because your load event isn't calling it. So, inside your Page_Load function.
public void Page_Load(object sender, EventArgs e)
{
Page PreviousPage = Page.PreviousPage;
if (PreviousPage != null)
{
lblUserLogin.Text = ((TextBox)PreviousPage.FindControl("txtUser")).Text;
lblAppLogin.Text = ((TextBox)PreviousPage.FindControl("txtAppNum")).Text;
}
{
string _connStr = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
}
CheckRecord();
}
public void CheckRecord()
{
//get the connection
using (SqlConnection conn = new SqlConnection(#"Data Source=ServerInfo"))
{
//write the sql statement to execute
string sql = "select username FROM BLAA_users WHERE username = #username";
//instantiate the command object to fire
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
//attatch the parameter to pass, if no parameter is in the sql no need to attatch
SqlParameter[] prms = new SqlParameter[1];
prms[0] = new SqlParameter("#username", SqlDbType.VarChar, 50);
prms[0].Value = lblUserLogin.Text.Trim();
cmd.Parameters.AddRange(prms);
conn.Open();
object obj = cmd.ExecuteScalar();
conn.Close();
if (obj != null)
{
Response.Redirect("~/WebForm1.aspx");
}
else
Response.Redirect("http://www.google.com");
}
}
}
Another ASP.NET C# noobie question...
The following codebehind populates a dropdown list from a database. There are three columns in the table (ID, ItemType & BinType). I need to be able to return the correct BinType for the row selected by the user:
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.Configuration;
using System.Data.SqlClient;
using System.Data.OleDb;
public partial class _Default : System.Web.UI.Page
{
// Global variable for SqlConnection
OleDbConnection con = new OleDbConnection();
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
// specifying sqlconnection string
con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString_GRPAS_dev"].ConnectionString;
{
// Select rows from database where the ItemType field isn't empty. Sort them alphabetically by ItemType
using (OleDbCommand cmd = new OleDbCommand("SELECT * FROM NF_WhatWasteWhere WHERE ItemType <>'' Order By ItemType"))
{
//Open the connection and populate the dropdown list with ID and Itemtype
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
ItemType1.DataSource = cmd.ExecuteReader();
ItemType1.DataTextField = "ItemType";
ItemType1.DataValueField = "ID";
ItemType1.DataBind();
con.Close();
}
}
// Add a non selectable "Select Item" row at the top of the dropdown list
ItemType1.Items.Insert(0, new ListItem("--Select Item--", "0"));
}
}
protected void ItemType1_SelectedIndexChanged(object sender, EventArgs e)
{
//
// *** Stuff needs to go here in order to continue with the following conditional statement ***
//
if (ItemType1.SelectedValue == "Green")
{
BinResultTest.Text = "<div class='greenBin results'><div class='arrow'></div><p>" + ItemType1.SelectedItem + " should be disposed of in a <strong>green bin</strong>.</p></div>";
}
else if (ItemType1.SelectedValue == "Black")
{
BinResultTest.Text = "<div class='blackBin results'><div class='arrow'></div><p>" + ItemType1.SelectedItem + " should be disposed of in a <strong>black bin</strong>.</p></div>";
}
else
{
BinResultTest.Text = "<div class='noBin results'><div class='arrow'></div><p>" + ItemType1.SelectedItem + " should <strong>NOT</strong> be disposed of in a green or black bin.</p></div>";
}
}
}
What do I need to do to get the conditional statement to work? I presume I need to run another database query - something like the following:
SELECT BinType FROM NF_WhatWasteWhere WHERE ID=" + ItemType1.DataValueField
However, I'm not sure how to code this to establish the connection and return the result.
Any help appreciated.
Thanks.
Edit***
Okay then in protected void ItemType1_SelectedIndexChanged(object sender, EventArgs e)
You can do something similar to what you did with your first query but use an OdbcDataReader
string binValue;
int idHolder = ItemType1.SelectedValue;
con.ConnectionString =System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString_GRPAS_dev"].ConnectionString;
{
using (OleDbCommand cmd = new OleDbCommand("SELECT BinType FROM NF_WhatWasteWhere WHERE ID = #Id;"))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#Id",idHolder);
cmd.Connection = con;
con.Open();
OleDbDataReader reader = cmd.ExecuteReader();
if(reader.Read())
{
if(!DBNull.Value.Equals(reader["BinType"]))
{
binValue = Convert.ToString(reader["BinType"]);
}
}
con.Close();
//Then all your conditionals based off of binValue....
Something like this but maybe a bit more well writen.
I am changing a console app login over to a web based application and recieve the following error about an Unhandled exception.
In the console app I have the following line of code which resides in the StoredProcDemo class:
StoredProcDemo spd = new StoredProcDemo();
In the Web Application I have:
Login spd = new Login();
I am not sure what to change it over to. Could someone shed some insight thanks and maybe why? Thanks so much.
Here is the full code if needed.
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.SqlClient;
using System.Data.Sql;
using System.Data.SqlTypes;
namespace GUI_Login
{
public partial class Login : System.Web.UI.Page
{
SqlConnection conn = null;
SqlParameter parmReturnValue;
Login spd = new Login();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnLogin_Click(object sender, EventArgs e)
{
RunStoredProcParams();
}
public void RunStoredProcParams()
{
//run simple stored procure
spd.RunStoredProcParams();
int Result;
Result = -1;
conn = conn = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=c:\\Program Files\\Microsoft SQL Server\\MSSQL10.SQLEXPRESS\\MSSQL\\DATA\\UserDB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True; Integrated Security=SSPI");
conn.Open();
try
{
//create and open a connection object
conn = conn = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=c:\\Program Files\\Microsoft SQL Server\\MSSQL10.SQLEXPRESS\\MSSQL\\DATA\\UserDB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True; Integrated Security=SSPI");
conn.Open();
//Create the command object indentifying the stored procedure
SqlCommand cmd = new SqlCommand("PassParamUserID", conn);
//set the command object so it knows to execute a stored procedure
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#FirstName", txtUserName.Text));
parmReturnValue = cmd.Parameters.AddWithValue("#UserId", SqlDbType.Int);
parmReturnValue.Direction = ParameterDirection.ReturnValue;
cmd.ExecuteNonQuery();
Result = Convert.ToInt32(cmd.Parameters["#UserId"].Value);
conn.Close();
// lblResult.Text = Result;
if (Result > 0)
{
lblResult.Text = ("User does exist in database");
}
else if (Result < 0)
{
lblResult.Text = ("Denied, try another user name");
}
}
finally
{
if (conn != null)
{
conn.Close();
}
}
}
Even ignoring RunStoredProcParams you'll get a stack overflow as soon as you try to create a new instance:
public partial class Login : System.Web.UI.Page
{
// Removed extraneous stuff...
Login spd = new Login();
}
Why do you want every instance of Login to have a reference to another instance of Login, which it creates immediately?
Basically the constructor is going to be called recursively until it goes bang.
What are you trying to do here, and why? In the console app you may well be creating an instance of StoredProcDemo, but I'm sure it wouldn't be within StoredProcDemo itself (as an instance variable initializer). Perhaps it's in Program or something similar? That would make more sense.
You run RunStoredProcParams() recursively indefinitely.
Comment out this line:
spd.RunStoredProcParams();
Also comment this one:
Login spd = new Login();