Why won't C# show the table - c#

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

Related

MySQL connection to a win form app in visual studio 2019

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/

Calling class from code behind

I am still new to ASP.net and I'm learning how to call classes. I've looked around for tutorials, but not all are specific to ASP.net 4.0 so I'm not sure if I should apply them.
Right now, I am trying to connect to my SQL database. My webconfig file has been set up with the connectionstring "dbConnectionString" and is working properly when I've tested it with GridViews. What I'd like to do now is access the database from code behind.
I've seen some ways to accomplish this, but I'd like the most efficient, resuable way. I've tried to adopt the answer listed here: How to create sql connection with c# code behind, access the sql server then conditionally redirect? however, I'm getting an error.
I am doing this with C# as a website, not a web application. Here is my code behind for Login.aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SqlComm; // Is this how I connect to my class from this page????
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
//no code written yet
}
}
}
My class in the App_Code folder, file name SQLComm.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Web;
/// <summary>
/// SQL Query class
/// </summary>
public class SqlComm
{
// Connection string
static string DatabaseConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["dbConnectionString"].ConnectionString;
// Execute sql command with no value to return
public static void SqlExecute(string sql)
{
using (SqlConnection conn = new SqlConnection(DatabaseConnectionString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}
}
// Execute SQL query and return a value
public static object SqlReturn(string sql)
{
using (SqlConnection conn = new SqlConnection(PjSql.dbcs()))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
object result = (object)cmd.ExecuteScalar();
return result;
}
}
// Retrieve an entire table or part of it
public static DataTable SqlDataTable(string sql)
{
using (SqlConnection conn = new SqlConnection(DatabaseConnectionString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Connection.Open();
DataTable TempTable = new DataTable();
TempTable.Load(cmd.ExecuteReader());
return TempTable;
}
}
// Execute a stored procedure with 1 parameter
// Returning a value or just executing with no returns
public static object SqlStoredProcedure1Param(string StoredProcedure, string PrmName1, object Param1)
{
using (SqlConnection conn = new SqlConnection(DatabaseConnectionString))
{
SqlCommand cmd = new SqlCommand(StoredProcedure, conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter(PrmName1, Param1.ToString()));
cmd.Connection.Open();
object obj = new object();
obj = cmd.ExecuteScalar();
return obj;
}
}
}
As you can see, I haven't written any code to actually use the class yet, but the "using SQLComm;" line itself is giving me this error:
Compiler Error Message: CS0246: The type or namespace name 'SqlComm' could not be found (are you missing a using directive or an assembly reference?)
As I'm still new, I'm unsure where to go from here. I seem to have included everything contained in the answer on the page I linked above. What else and I missing?
Edit: I read this post regarding a similar issue: asp.NET 2.0 Web Site Can't Access Classes in App_Code
Could this be because I am doing a website and not a web application, so the App_Code folder is being handled differently when I FTP the files over?
using SQLComm means you want to use the namespace SqlComm, which doesn't exist. I think what you want is (somewhere in your codebehind):
DataTable dt = SqlComm.SqlDataTable(...) // call one of the static methods.
You can call it directly.
Given your class has static methods only you'll call it like this:
SqlComm.SqlReturn("select * from table");
So I believe I figured it out. I had my App_Code folder within the subdirectory of my Aspx website, instead of in the root of the server. I moved the folder to the root and now it's working.
I'd be interested in hearing any answers to my edit to my original post though. Since I'm doing this as a website instead of a web application, are there any other issues I will need to keep in mind regarding using classes like this or other issues? I've looked around but haven't seen many differences.
Thanks to everyone for you help!

removing form from c# code?

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.

Asp.Net Application Database Connection issue

When I try to write in C# a connection to my app to my database, I build the application successfully in Visual Studio 2005 but when I run the site in debugger i get an error:
Exception Details: System.ArgumentException: Format of the initialization string does not conform to specification starting at index 118.
Here is the connection code that is giving the error:
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Server"].ConnectionString);
I have the connection string written correctly in my web.config, file so im clueless on what this remotely means. Im not sure if im missing anything. Any help appreciated. Here is my entire code for the section that might help:
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;
using System.Web.Configuration;
using System.Data.SqlClient;
public partial class RateAnalyzerPage: System.Web.UI.Page
{
protected void Search_Click(object sender, EventArgs e)
{
string IDnumber = mechantNumber.Text;
string selectSQL = "SELECT FROM Authors Where MID='"+ IDnumber +"'";
// SqlConnection con = new SqlConnection(#"Server=");
//SqlConnection con = new SqlConnection();
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["Server"].ConnectionString);
SqlDataReader reader;
try
{
con.Open();
SqlCommand cmd = new SqlCommand(selectSQL, con);
reader = cmd.ExecuteReader();
while (reader.Read())
{
QualVol.Text = reader["TotalVolume"].ToString();
}
reader.Close();
}
catch (Exception err)
{
}
finally
{
con.Close();
}
}
}
Let me know if im missing some data that would help.
Heres the connection string:
I've separated out and XML decoded the connection string value:
Data Source=Server;Initial Catalog=Odata;Integrated Security=True;MultipleActiveResultSets=False;Packet Size=4096;Application Name="Microsoft SQL Server Management Studio"User ID=Name;Password=PW
As you can see, you're missing a ; between Application Name and User ID. I'm not sure if that's the issue, but it's possible.
Your connection string use the Integrated Security=True, but the right syntax is
Integrated Security=SSPI; or Trusted_Connection=True so change it and remove the UserId and Password.
(or remove Integrated Security=True and leave UserID and Password)
Try to change something in your code.
protected void Search_Click(object sender, EventArgs e)
{
string IDnumber = mechantNumber.Text;
string selectSQL = "SELECT * FROM Authors Where MID=#num";
using(SqlConnection con = new SqlConnection
(System.Configuration.ConfigurationManager.ConnectionStrings
["Server"].ConnectionString))
{
SqlDataReader reader;
con.Open();
SqlCommand cmd = new SqlCommand(selectSQL, con);
cmd.Parameters.AddWithValue("#num", IDNumber);
reader = cmd.ExecuteReader();
while (reader.Read())
{
QualVol.Text = reader["TotalVolume"].ToString();
}
reader.Close();
}
}
Try to use the using statemend, this guarantees the disposing of your connection
Try to use parametrized query, this avoid Sql Injection attacks and quoting problems
Also SELECT requires a fields list or *
I think Jacob has it right. On a side note, don't do this:
string selectSQL = "SELECT FROM Authors Where MID='"+ IDnumber +"'";
This will lead to sql injection attacks, just like the one that was used to get yahoo user accounts last week.
Do this instead:
string selectSQL = "SELECT * FROM Authors Where MID=#ID";
cmd.Parameters.AddWithValue("#ID", IDnumber );

Where/how do I write T-SQL in my C# code and get the result (Visual Studio 2008)

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

Categories

Resources