.NET and sql server database link - c#

I'm a real noob in .NET and i'm trying to link a simple command line application (in C#) with a SQL server database. I'm now able to connect the program with the database but not to recover the data that are in it. Here is my code :
using System;
using System.Data;
using System.Data.SqlClient;
namespace ConsoleApplication1
{
class Program
{
static void Main()
{
string connectionString = GetConnectionString();
string queryString = "SELECT USER_ID FROM dbo.ISALLOCATEDTO;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = connection.CreateCommand();
command.CommandText = queryString;
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
int i = 0;
while (reader.Read())
{
i++;
Console.WriteLine("Field "+i);
Console.WriteLine("\t{0}",reader[0]);
}
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
//Console.WriteLine("Hello world");
string x = Console.ReadLine();
}
static private string GetConnectionString()
{
return "Data Source=FR401388\\SQLEXPRESS;Initial Catalog=Test;";
+ "Integrated Security=SSPI";
}
}
}
But when i'm running it and even if my table is not empty (I've seen it in the sql server studio), I cannot recover the data by using the read() method.
What I've done so far : try to change the name of the datatable with a fake one : the datatable is not found (so the link between sql server database and programm seems to be valid).
I'm using Windows Authentication in sql server, dunno if it's changing anything... (Once again : i'm very new to all of that).
Thanks !

Your code should work.
A possible cause is: You are looking at a different database.
This is quite common if you use Server Explorer inside VS with a connectionstring different from the one used in code.

Related

The application freezes when I try to update timestamp column with a placeholder in an Oracle database using C#

I am trying to update 2 columns in an Oracle database using C#. The columns I want to update are StartTime i.e. a timestamp and Name i.e. string. However when I run my code, the application freezes. I following is my code:
public int StartProduction(string serialNr, string empName)
{
string queryString = "UPDATE RO_EXEMPLAAR_PIM SET PLAKTAFEL_START=systimestamp, STARTED_BY=:startedBy WHERE SERIENR=:serialNr";
using (OracleConnection connection = new OracleConnection(connectionString))
{
using (OracleCommand command = new OracleCommand(queryString, connection))
{
try
{
OracleDataAdapter da = new OracleDataAdapter();
connection.Open();
command.Parameters.AddWithValue("serialNr", serialNr);
command.Parameters.AddWithValue("startedBy", empName);
da.InsertCommand = command;
int nrOfRecordsChanged = command.ExecuteNonQuery();
return nrOfRecordsChanged;
}
catch
{
return -1; //which means the try-block was not executed succesfully
}
finally
{
connection.Close();
}
}
}
}
I call it in a form as this:
if (dh.StartProduction(serialNr, empName) != -1)
{
MessageBox.Show("Production started successfully!");
}
else
{
MessageBox.Show("Production cannot be started!");
}
I looked up online and could not find what is wrong with my code. Thanks in advance!
Try a non locking read query like;
SELECT * FROM V$VERSION;
If that works (proving your connection string works).
Then you probably have a locking issue.
In general: (especially for devs)
Make sure you are not missing a "commit;" in your sql-developer or dbvisualizer or something like that. (or somebody on your dev team).
Running an update without a "commit;" in side these tools will lock a row.
If you can't find the culprit : a reboot of the server is in order.

MySQL insert C# fails when Connection Pooling is activated

I have the following INSERT method in a C# web project. If I run the project without MySQL connection poling everything works fine, but when I activate Pooling=True in the DB connection string this method stops working, the insert statements never complete.
I realized how to modify the code to make it work, but I would like to understand what is happening and I hope you could help.
When I comment line //myR.Close(); everything works fine.
using MySql.Data.MySqlClient;
//query example consulta="INSERT INTO users (id, name) VALUES (1, 'Rob');
public static MySqlConnection GetWriteConnection()
{
string connStr = MySqlConnectionStrings.WriteConnectionString;
MySqlConnection conn = new MySqlConnection(connStr);
return conn;
}
public static MySqlConnection GetReadConnection()
{
string connStr = MySqlConnectionStrings.ReadConnectionString;
MySqlConnection conn = new MySqlConnection(connStr);
return conn;
}
public static bool Insert(string consulta)
{
MySqlConnection conn = BdaHelper.GetWriteConnection();
conn.Open();
using (conn)
{
try
{
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
MySqlCommand micomando = new MySqlCommand(consulta, conn);
micomando.ExecuteNonQuery(); //still not working
return true;
}
catch (Exception ex)
{
return false;
}
}
}
My app has also multi-thread concurrency and two types of database connections, one specifically for only-read purposes and other different for write. When an insert statement fails I don't get any error simply the change doesn't commit in the database. Reading the article in the comments I don't think this applies to this issue but I would add an example of my main program:
MySqlConnection readConnection = BdaHelper.GetReadConnection();
using (readConnection)
{
var users = GetUsers(readConnection);
var credentials = GetCredentials(readConnection);
//Example is the query that fails don't giving any exception
Insert("INSERT INTO login_log (id_user, date) VALUES (1, now())");
}
May the problem be caused because there are two concurrent connections?
I shouldn't reuse read connection, even is a different connection than the write connection?

Execute any Raw SQL Query

IS it possible to execute a raw SQL command of any type (SELECT, UPDATE, DELETE....) in C#. I am looking to add a feature similar to the SQL Server Management Studio query window where I can just type in any SQL command and it executes it. In my case I am not worried about sql injection, I know this risk with this feature. All the connection parameters are passed to me (I have a valid connection string), but I know nothing about the database itself. The SQL command is also syntactically correct before I get the command. I cannot seem to find a solution that will work in all cases, probably just overlooking the obvious solution.
Here is an ADO example for you
using System;
using System.Data;
using System.Data.SqlClient;
class Program
{
static void Main()
{
string connectionString =
"Data Source=(local);Initial Catalog=Northwind;"
+ "Integrated Security=true";
// Provide the query string with a parameter placeholder.
string queryString =
"UPDATE [dbo].[USR_Users] SET [Active] = 1 WHERE Id = 1";
using (SqlConnection connection =
new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
}
You can simply use ADO .NET and show the results of the query if it executed successfully or not, just put the following code in the event handler when you want to execute your query:
using (SqlConnection conn = ConnectionClass.GetInstance().Connection())
using (SqlCommand cmd = new SqlCommand(TextBoxQuery.Text, conn))
{
conn.Open();
TextBoxNoOfRowEffected.Text = cmd.ExecuteNonQuery().ToString();
}
SqlCommand.ExecuteNonQuery() Documentation

Strange behaviour of OracleDataReader in Read() method

Hi all Oracle experts,
I have a rather strange behaviour of a very very simple program only intended to test basic data acquisition from a remote Oracle database with C#.
I have created a simple C# program as follows:
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using Oracle.ManagedDataAccess.Client;
class Program
{
static void Main(string[] args)
{
var connectionString = "Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP) (HOST={{Server}})(PORT=1521)))(CONNECT_DATA=(SERVICE_NAME={{DataSource}})));User Id={{Username}};Password={{Password}};";
connectionString = connectionString.Replace("{{DataSource}}", "Actual service name");
connectionString = connectionString.Replace("{{Server}}", "Actual Server IP");
connectionString = connectionString.Replace("{{Username}}", "Actual username");
connectionString = connectionString.Replace("{{Password}}", "Actual password");
using (connection = new OracleConnection {ConnectionString = connectionString})
{
connection.Open();
using ( var cmd = connection.CreateCommand() )
{
cmd.CommandText = "SELECT * FROM Table";
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
i++;
}
}
}
}
}
}
The table I am reading from has 220.000 entries, and the problem with the code is, that after an amount of "rows" the reader.Read() just stops. It is supposed to return "false" if there are no more records, and there are still records to come, but the Read() function is called and never returns. Even after letting it try for hours it does not come back.
Does anyone have had a similar experience?
I already heard not to use the Microsoft Oracle Data Driver, so I am using the one from oracle. But still the problem does not go away.
The amount of rows retrieved changes if you change the SQL Command, but also not in a very understandable way: I thought if this has to do with the network buffers I can reduce the columns to get more rows, but it works in the opposite direction. More columns result in more rows.
Any help is deeply appreciated.

Why won't C# show the table

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

Categories

Resources