I can't get the form design to work my project compiles perfectly, but when I try to get click my button the file say key word not supported "allowloadlocalinfile"
I copied and paste what i thought was the connection string
server=localhost;userid=root;database=resume;persistsecurityinfo=True;allowloadlocalinfile=False;sslmode=None
but i get this error
here is my interface code
using System;
using System.Data.SqlClient;
using System.Windows.Forms;
using System.Windows.Forms;
namespace Resume2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("server=localhost;userid=root;database=resume;persistsecurityinfo=True;allowloadlocalinfile=False;sslmode=None");
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO fields VALUES (#ResumeF_Name,#ResumeL_Name)",
con);
cmd.Parameters.AddWithValue("#ResumeF_Name", textBox1.Text);
cmd.Parameters.AddWithValue("#ResumeL_Name", textBox2.Text);
cmd.ExecuteNonQuery();
con.Close();
}
}
}
I leave out the id column because it is set to auto_increment but he other to columns in my MySQL database "resume" table "fields" are ResumeF_Name and Resume_L_Name
now it's saying the connection string is server=localhost;user id=root;database=resume but still have a popup error
You have to use a connectionString for MySql instead of MS SQL.
Here are the main steps:
You have to add the nuget package "MySql.Data" to your project
Then you have to add the using using MySql.Data.MySqlClient(); to your code
You can then use this MySqlConnection cnn = new MySqlConnection("Server=localhost;Database=resume;Uid=root;Pwd=yourPassword;");
If you need some information about the connectionString for MySql. You can find out more information at this website: https://www.connectionstrings.com/mysql-connector-net-mysqlconnection/
Related
I'm pretty new to SQL Databases & C# language, I can't add data to my SQL Database from my web application despite doing everything correctly? I'm currently training in Azure SQL & C# & have been using the following training video:
https://www.youtube.com/watch?v=POWm4EfU9bA
I'm using MS Visual Studio and MS SQL Server Management Studio, I'm also using Azure Web + SQL service and I have opened up the firewall allowing my client IP address through.
Can anyone work out, from my code, why I my data from my webform isn't being added to my database? Here is my coding which "apparently" adds data to my SQL database from the form located in my front end web application:
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
namespace bluecitywebapplication
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == true)
{
Label1.Text = ("Great job!");
}
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection stormconn = new SqlConnection("Server=tcp:bluecitydb.database.windows.net,1433;Initial Catalog=xxx;Persist Security Info=False;User ID=xxx;Password=xxx;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;");
{
SqlCommand insert = new SqlCommand("EXEC dbo.InsertFullname #Fullname", stormconn);
insert.CommandType = System.Data.CommandType.StoredProcedure;
insert.Parameters.AddWithValue("#Fullname", TextBox1.Text);
insert.Parameters.AddWithValue("#Address", TextBox2.Text);
insert.Parameters.AddWithValue("#Email", TextBox3.Text);
stormconn.Open();
insert.ExecuteNonQuery();
stormconn.Close();
if (IsPostBack)
{
TextBox1.Text = ("");
}
}
}
}
}
sorry, I apologize for the mistake, I thought that you are facing connection issue in your question. I read the code carefuly i found there is issue in the code of executing procedure. I updated the code.
protected void Button1_Click(object sender, EventArgs e)
{
using (var connection = new MySqlConnection("Server=tcp:xxxx.database.windows.net,1433;Initial Catalog=xxxx;Persist Security Info=False;User ID=xxxxx;Password=xxxxx;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"))
{
MySqlCommand command = new MySqlCommand("InsertFullname", connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new MySqlParameter("Fullname", TextBox1.Text));
command.Connection.Open();
var result = command.ExecuteNonQuery();
command.Connection.Close();
}
}
stackoverflow community! Once more, I come here seeking for your help...
My problem is: I have made a c# application used to register accounts in a MySQL database hosted by Byethost (SecureSignup). The connection works, but not all the time, even though no conditions are changed.
One minute I can submit the query and PhpMyAdmin shows it as beeing written in the database, but a few minutes later, when I try the exact same thing, I get various timeout errors ranging from "Unable to read data from the transport connection: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond." to "Timeout IO Operation"... Here is my code, maybe having it could help you understand why it has such a strange behaviour from time to time, because I sure can't.
(I have granted my IP remote MySQL access from the cpanel, and the login data are 100% correct)
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 MySql.Data.MySqlClient;
namespace Main
{
public partial class Form1 : Form
{
string connString;
MySqlDataReader reader;
MySqlConnection conn;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
connString = "Server=sql.byethost46.org;Port=3306;Database=bleachon_aza;UID=bleachon;password=********";
conn = new MySqlConnection(connString);
MySqlCommand command = conn.CreateCommand();
command.CommandText = "INSERT into users (Username,password) VALUES('" + usr.Text + "','" + pass.Text + "')";
conn.Open();
int timeoutvalue = conn.ConnectionTimeout;
command.ExecuteNonQuery();
MessageBox.Show(timeoutvalue.ToString()); //This was a curiousity, it displays 15
conn.Close();
}
}
}
You should use parameters to prevent SQL injection.
Also use the using statement to properly dispose your MySQL objects.
private void button1_Click(object sender, EventArgs e)
{
connString = "Server=sql.byethost46.org;Port=3306;Database=bleachon_aza;UID=bleachon;password=********";
using (conn = new MySqlConnection(connString))
{
string query = "INSERT INTO users (Username, password) VALUES (#usr, #pass)";
// are you sure your column name is Username and not username ?
conn.Open();
using (MySqlCommand cmd = new MySqlCommand(conn, query))
{
cmd.Parameters.AddWithValue("#usr", usr.Text);
cmd.Parameters.AddWithValue("#pass", pass.Text);
cmd.ExecuteNonQuery();
// No need to close your connection. The using statement will do that for you.
}
}
}
As for the connection problems, I think you should contact your host for answers. I use MySql all the time using C#, without any problems, so i think it's a problem with your hosting.
I'm extremely new to C# and programming anything except for SQL. I've gotten the below code to happen on a Form and on a button click. If I wanted to just make this run on open, how would I do that? I'm very new to C# as you can tell (just started today learning it but its pretty exciting!)
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 Oracle.DataAccess.Client; // ODP.NET Oracle managed provider
using Oracle.DataAccess.Types;
namespace OraTrigger
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string oradb = "Data Source=OMP1;User Id=user;Password=pass;";
OracleConnection conn = new OracleConnection(oradb); // C#
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT cast(Count(*) as varchar(20)) as trig FROM ZDMSN.TRIGGER_TEST";
//cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();
dr.Read();
int cnt;
if (int.TryParse(dr.GetString(0), out cnt))
{
if (cnt > 0)
{
System.Diagnostics.Process.Start(#"C:\testfile.bat");
}
}
cmd.CommandText = "TRUNCATE TABLE ZDMSN.TRIGGER_TEST";
conn.Dispose();
}
}
}
If you need to run your code as a scheduled task then a command line application is more suitable.
Just create a new project and select Console Application.
Then move all of your button click code inside the Main method written for you by the Visual Studio IDE.
Rembember to set the references to the Oracle ODP.NET library and import the relevant using statements
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Oracle.DataAccess.Client; // ODP.NET Oracle managed provider
using Oracle.DataAccess.Types;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string oradb = "Data Source=OMP1;User Id=user;Password=pass;";
using(OracleConnection conn = new OracleConnection(oradb))
using(OracleCommand cmd = new OracleCommand("SELECT Count(*) as trig FROM ZDMSN.TRIGGER_TEST", conn))
{
conn.Open();
int cnt = (int)cmd.ExecuteScalar();
if (cnt > 0)
{
System.Diagnostics.Process.Start(#"C:\testfile.bat");
cmd.CommandText = "TRUNCATE TABLE ZDMSN.TRIGGER_TEST";
cmd.ExecuteNonQuery();
}
}
}
}
}
I have also revised your code to get a single value from the database. For this case is enough to use the Command.ExecuteScalar method that returns the first column of the first row obtained from your sql command text. Because the count(*) should Always return a single row you could easily cast the return value of ExecuteScalar to your record count variable.
EDIT I have added the logic to TRUNCATE the table involved. Please pay attention that you should use the code provided here. Your code will probably fail because you have an open DataReader and when a DataReader is open you cannot execute other commands (This is true for SqlServer without Multiple Active Result Sets enabled, I really don't know if this rules applies also to the Oracle NET Provider)
Subscribe to Shown or Load event of form and move your code to that event handler.
Form.Shown Event Occurs whenever the form is first displayed.
Form.Load Event Occurs before a form is displayed for the first time.
Also I suggest to extract your code to some Data Access related class, or at least to separate method. And call that method from event handler.
I'm using Visual Web Developer 2010 Express and SQL Server 2008 R2 Management Studio Express
Hey guys,
Pretty new at C# here. I'm trying to follow this C# ADO.NET tutorial (currently on step 2), and I'm stumped. I'm following all the steps, and everything makes sense to me in it, but whenever I try to debug, it does not show anything (in the sense of the c# methods not printing out a table from Northwind database onto my webpage) in WebApplication1's Default.aspx page.
For a while, I thought it was my connection string, conn, and I wasn't naming the "Data Source" attribute, which from my understanding is the name of the server I'm trying to connect to. It is all on a local machine, and I'm putting the correct server name.. I think. Server name is AZUES-221\JDOESQLSERVER
I'm properly escaping the backward slash, but I still don't know. Is there something in my coding that's flawed? Please help!
C# code
using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
namespace WebApplication1
{
public partial class SqlConnectionDemo : System.Web.UI.Page
{
protected void Main(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=AZUES-221\\JDOESQLSERVER; Initial Catalog=Northwind; Integrated Security=SSPI");
SqlDataReader rdr = null;
try
{
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM Customers", conn); //passed the connection
rdr = cmd.ExecuteReader(); // get query results
while (rdr.Read()) //prints out whatever was
{ Console.WriteLine(rdr[0]); }//selected in the table
}
finally
{
if (rdr != null)// closes
{ rdr.Close(); }// the reader
if (conn != null)//closes
{ conn.Close(); }// the connection
}
}
}
}
Thanks in advance
As your example seems to be a WebProject try to put your code within Page_Load eventHandler. Afterwards you should try to print your data to the Debug window or to a control within your webPage.
using System;
using System.Data;
// and all the others ...
namespace WebApplication1
{
public partial class SqlConnectionDemo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=AZUES-221\\JDOESQLSERVER; Initial Catalog=Northwind; Integrated Security=SSPI");
SqlDataReader rdr = null;
try
{
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM Customers", conn);
rdr = cmd.ExecuteReader(); // get query results
while (rdr.Read()) //prints out whatever was
{
System.Diagnostics.Debug.WriteLine(rdr[0]); // or on the other hand
lblOutput.Text += rdr[0]; // as a "quick and dirty" solution!
}
}
finally
{
if (rdr != null)// closes
{ rdr.Close(); }// the reader
if (conn != null)//closes
{ conn.Close(); }// the connection
}
}
}
}
You may it find very useful to have a look at databound controls or just use another type of project (eg winForm, console, ...)
Create a Console application instead of the Web Application you have created.
Otherwise you will run into similar issues considering you are new to C# (or Visual Studio in general) AND considering the rest of the tutorial uses Console.WriteLine heavily.
Then you can use the same code as shown in the tutorial.
Additonally if you are concerned about the slash in the database server (it is a database server instance), you may wanna try this:
SqlConnection conn = new SqlConnection(#"Server=AZUES-221\JDOESQLSERVER;Database=Northwind;Trusted_Connection=True;");
Source: Connection Strings Reference
why would console.writeline show anything. you are not working on console.
in case just to see your output. use Response.writeline(rdr[0]);
I am trying to write t-sql in C# (visual studio). I have this code to connect to the database:
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.Data.SqlClient;
using Microsoft.SqlServer.Server;
namespace WindowsFormsApplication8
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection cnn;
connetionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\Xtreme\\Desktop\\CardsDB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";
cnn = new SqlConnection(connetionString);
try
{
cnn.Open();
MessageBox.Show("Connection Open ! ");
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
}
}
Where/how do I write the T-SQL code and how do I get the result?
Can someone give me an simple select example in my code?
You can use DataAdapter.Fill Method:
try
{
using (SqlDataAdapter a = new SqlDataAdapter("SELECT * FROM Employee", cnn))
{
// Use DataAdapter to fill DataTable
DataTable t = new DataTable();
a.Fill(t);
// Render data onto the screen
dataGridView1.DataSource = t; //if you want.
}
}
catch (Exception ex)
{
MessageBox.Show("Problem!");
}
Create a SqlCommand and set the CommandType to CommandType.Text. Then add your SQL to the CommandText property of the SqlCommand.
SqlCommand command = new SqlCommand(commandName, (SqlConnection)Connection);
command.CommandType = CommandType.Text;
command.CommandText = "SELECT * FROM MyTable";
IDataReader result = command.ExecuteReader();
Ardman already showed you how to execute any arbitary sql command. But what i didn't answer very well, is where to put your sql statement.
I think it is a very bad behaviour and also not very good to read if you put your statement directly into the code.
A better method (in my eyes) is the following:
Within your project create a new folder (maybe called Queries)
Right click this folder and select Add - New Item
In the dialog just select Textfile and give it the name about what this query will do
Make sure you replace the file extension from .txt to .sql
Just put your statement right into this file
In the Resource Editor add this file as a resource
Now you can access this sql statement within your project just by using Properties.Resources.MySqlStatement