Through the information I have found searching here on stackoverflow, I have what I think is 90% of this solved but because of how OleDbConnection is converted to define SqlConnection, the call to the class with the connection and test script wants definition I am unsure how to provide.
I've used these pages to get what I have so far
How to create an SqlConnection in C# to point to UDL file
Calling an SQL Connection method in C#
private static string CONNECTION_NAME = #"C:\Temp\DisplayDB.udl";
public static class MyConnection
{
public static SqlConnection GetSqlConnection()
{
var udlInfo = new OleDbConnection($"File Name={CONNECTION_NAME}");
return CreateSqlConnection(udlInfo);
}
public static SqlConnection CreateSqlConnection(OleDbConnection udlInfo)
{
try
{
string CONNECTION_STRING = $"Database={udlInfo.Database};Server={udlInfo.DataSource};User ID=User;Password=13245;Integrated Security=True;connect timeout = 30";
var connection = new SqlConnection(CONNECTION_STRING);
connection.Open();
return connection;
}
catch
{
Console.WriteLine($"{CONNECTION_NAME} Not found");
return null;
}
}
}
private void DBCheck()
{
// The line below is my issue, mouseover error of ".CreateSqlConnection"
// says there is no argument given that corresponds to the required
// formal parameter 'udlInfo' of
// 'MainWindow.MyConnection.CreateSqlConnection(OleDbConnection)'
using (var con = MyConnection.CreateSqlConnection())
{
con.Open();
var command = new SqlCommand("IF DB_ID ('CodeTest') IS NULL " +
"BEGIN " +
"USE MASTER " +
"CREATE DATABASE CodeTest" +
" END", con);
var reader = command.ExecuteReader();
reader.Close();
con.Close();
}
}
I expect the WPF to use the Database and Server from the UDL file to make the SqlConnection so I can run queries and commands. I understand the security part of UDL in plain text but I do not want hard coded values as this application will be used in various environments nor do I want those values to need definition on each launch of the app.
Related
I am new to .Net and C# and I have been struggling to get my head round on how to utilise a sql connection created in one section of the code and use it in another. I got 2 buttons on my form. One connects to the database and the other inserts to a table. How do I use the connection variable when inserting to the table?
I hope this makes sense. Thanks
namespace SQL
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnConnect_Click(object sender, EventArgs e)
{
SqlOperations connect = new SqlOperations();
connect.connectToSQL("server=localhost\\SQLExpress;", "database=Cromwell; ");
}
private void btnAddToDatabase_Click(object sender, EventArgs e)
{
SqlOperations addToTable = new SqlOperations();
addToTable.InsertToTable("InputDir", "C:\\");
}
}
public class SqlOperations
{
public bool connectToSQL(string sqlHost, string database)
{
SqlConnection SqlConnect = new SqlConnection("user id=userid;" +
"password=validpassword;" + sqlHost +
"Trusted_Connection=yes;" +
database + "connection timeout=30");
try
{
SqlConnect.Open();
MessageBox.Show("Connected to SQL Express");
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
return false;
}
}
public bool InsertToTable(string columnName, string value)
{
SqlCommand myCommand = new SqlCommand();
myCommand.Connection = **SqlConnect**; // THIS BIT COMPLAINS
myCommand.CommandText = "INSERT INTO Config (" + columnName + ") " +
"Values ('" + value + "')";
}
}
}
Solution 1: You can create your connection string as constant string variable and access it using class name from whereever you need it as constant variables are implicitly static(you can access them as global variables)
Try This:
Class MyConnectionString
{
const string strCon="user id=userid;password=validpassword;
server=localhost\\SQLExpress;database=Cromwell;
Trusted_Connection=yes;connection timeout=30";
}
while accessing :
SqlConnection scon=new SqlConnection(MyConnectionString.strCon);
Solution 2:
Create your connection string in Configuration file and access it.
<connectionStrings>
<add name="myConString"
connectionString="user id=userid;password=validpassword;
server=localhost\\SQLExpress;database=Cromwell;
Trusted_Connection=yes;connection timeout=30" />
</connectionStrings>
use it whenever you need it:
string ConnectionString =
ConnfigurationManager.ConnectionStrings["myConString"].ConnectionString;
Check this link, http://www.codeproject.com/Articles/4416/Beginners-guide-to-accessing-SQL-Server-through-C . It is a beginners guide to access SQL Databases using c#.NET.
You can also add the connection string in your web.config, or app.config and then access it from c# code.
C#
// Add a reference at the top of your code file
using System.Configuration;
// Within the code body set your variable
string cs = ConfigurationManager.ConnectionStrings["connectionStringName"].ConnectionString;
VB
' Add a reference at the top of your code file
Imports System.Configuration
' Within the code body set your variable
Dim cs as String = ConfigurationManager.ConnectionStrings("connectionStringName").ConnectionString
Obviously remember to add this (With your own connection string) in your web.config
<connectionStrings>
<add name="ConnStringDb1" connectionString="Data Source=localhost;Initial Catalog=YourDataBaseName;Integrated Security=True;" providerName="System.Data.SqlClient" />
I like that you've defined a class to connect to SQL. You can use that class to manage the lifecycle of your SQL connections, which is a good thing. It would also be good if it handled the connection credentials too so your callers don't have to know what it is. How about this:
public class SqlOperations
{
private SqlConnection Connect()
{
... Get SQL credentials here
... Open and return connection here
}
public bool InsertToTable(string columnName, string value)
{
using (var conn = Connect())
{
using (SqlCommand myCommand = new SqlCommand())
{
myCommand.Connection = conn;
... do your myCommand stuff here
}
}
}
}
Then in your form ditch the connect-to-db button - it's managed for you! All you need is your insert button with this event:
private void btnAddToDatabase_Click(object sender, EventArgs e)
{
SqlOperations addToTable = new SqlOperations();
addToTable.InsertToTable("InputDir", "C:\\");
}
The error with ExecuteReader: Connection property has not been initialized is giving me a fit. I think I have it set up right. I will show you how I create the mssql connection and then what I am requesting, and the class I created to read/write and open/close the connection. (Three different parts of the app but I just lumped them together so you could see the actual logic flow I hope.)
What am I missing, or where am I supposed to put the connection? Example? I appreciate the help!
Here is the using statement I start with:
using (MSSQL mssqldb = new MSSQL(Constants.msSqlServer, Constants.msSqlDb, Constants.msSqlUid, Constants.msSqlPswd))
Here is where I say "Hey, get me my data using my MSSQL class"
using (var results = mssqldb.Read("SELECT TOP 1 * FROM AlertLog ORDER BY AlarmID DESC"))
{
results.Read();
legacyAlert = Int32.Parse(results["AlarmId"].ToString().Trim());
}
Here is the MSSQL class
class MSSQL : IDisposable
{
public MSSQL(string server, string database, string uid, string pswd)
{
string msSqlConnectionString = #"Data Source=" + server + ";Initial Catalog=" + database + ";user id=" + uid + ";password=" + pswd;
SqlConnection msqlConnection = new SqlConnection(msSqlConnectionString);
msqlConnection.Open();
Console.WriteLine("MS SQL OPEN!");
}
public void Write(string sql)
{
using (SqlCommand myCommand = new SqlCommand(sql, msqlConnection))
myCommand.ExecuteNonQuery();
}
public SqlDataReader Read(string sql)
{
using (SqlCommand myCommand = new SqlCommand(sql, msqlConnection))
return myCommand.ExecuteReader();
}
public void Dispose()
{
try {
msqlConnection.Close();
}
catch (SqlException ex) {
Console.Error.WriteLine("MS SQL Error - Closing Database");
Console.Error.WriteLine(ex);
}
msqlConnection.Dispose();
}
private SqlConnection msqlConnection;
}
msqlConnection is null.
Your constructor creates a local variable named msqlConnection, but does not assign to the field.
i was making a simple windows application form, to register some people in a database, so i made a connection class there is it:
public void Query_send(string cmd)
{
String config = "server=127.0.0.1;uid=root;database=bdcliente;";
MySqlConnection conn = new MySqlConnection(config);
MySqlCommand comm = new MySqlCommand(cmd, conn);
try
{
conn = new MySql.Data.MySqlClient.MySqlConnection();
conn.ConnectionString = config;
conn.Open();
}
catch
{
MessageBox.Show("Error when connecting to the database!");
}
finally
{
conn.Close();
}
}
and then in the BUTTON to give the informations for the MySql i use this:
private void button1_Click(object sender, EventArgs e)
{
Query instance = new Query();
instance.Query_send("INSERT INTO `tbcliente`(`codCliente`, `name`, `cpf`, `telephone`) VALUES ([" + textBox1 + "],[" + textBox2 + "],[" + textBox3 + "],[" + textBox4 + "])");
}
i always get the error with the connection when i click the register button, may someone help me or give me a link of a tutorial that teaches the correct way of doing this?
Thanks, Iago.
My guess is that you need to wrap the VALUES clause results in single quotes as the SQL you are generating will be invalid.
VALUES ('" + textbox1 + "')
Brackets are only required when referring to table or column names. Not when you're referring to string literals.
Odd question, but have you tried applying a password to the database? Depending on the version of MySQL, I have had some issues with leaving the root password unassigned (on local machine you can be safe and just assign 'root' as the password as well). Another option would be to create a user account with permissions and try connection with those credentials.
Not sure if that will help, but it's process of elimination.
Also not sure if method was work in process, but even if it connected there was no execute command against the database.
public void Query_send(string cmd)
{
String config = "server=localhost;uid=root;database=bdcliente;";
MySqlConnection conn = new MySqlConnection(config);
MySqlCommand comm = new MySqlCommand(cmd, conn);
try
{
conn.Open();
comm.ExecuteNonQuery(); '--this was missing
}
catch
{
MessageBox.Show("Error when connecting to the database!");
}
finally
{
conn.Close();
}
}
I have been doing applications on Java, connected with MySQL, but now I am doing C# with Oracle.
Here is the code I've got so far:
using System.Data.OracleClient;
namespace Chat
{
class DBconnector
{
static private string GetConnectionString()
{
return "Data Source=myserver.server.com;Persist Security Info=True;" +
"User ID=myUserID;Password=myPassword;Unicode=True";
}
static public void ConnectAndQuery()
{
string connectionString = GetConnectionString();
using(OracleConnection conn = new OracleConnection())
{
conn.ConnectionString = connectionString;
conn.Open();
Console.WriteLine("State: " + conn.State);
Console.WriteLine("Connction String: " + conn.ConnectionString);
OracleCommand command = conn.CreateCommand();
string sql = "SELECT * FROM users";
command.CommandText = sql;
OracleDataReader reader = command.ExecuteReader();
while(reader.Read())
{
string myField = (string)reader["MYFIELD"];
Console.WriteLine(myField);
}
}
}
}
}
What is hacking me is that I don't know what to type in exchange of "myserver.server.com", "myUserID" and the "myPassword" in the connectionString.
I suppose it's "localhost/" and smth like that, but with Oracle I don't really have the same visual interface as with MySQL in the browser and thus I am kinda' lost.
I followed this tutorial: Instant Oracle using C#
and I am doing the case with including the connection String directly in my code, but not using the tsanames.ora external file.
Long story short -> I am not sure how to modify the connection string for my own database and if there are any other mistakes or suggestions - feel free to state them.
I'm not sure if you can do this without modifying your tnsnames, but it's not hard:
YOURSERVER = (DESCRIPTION = (ADDRESS = (PROTOCOL= TCP)
(Host= <your_server_hostname_or_IP>)(Port= <port>))(CONNECT_DATA = (SID = <DB_instance name>)) )
If you have doubts on how to fill these up, you should check with your nearest DBA.
Then just add YOURSERVER in:
return "Data Source=YOURSERVER; ...
Username and password are those related to the schema you want to connect.
in c sharp in win forms i am encountering an error, something like null reference exception
this is my code...and also I don't find any entries in the database table...
public partial class Form1 : Form
{
string strCon, strQry;
SqlConnection con;
SqlCommand cmd;
int rowsaffected;
public Form1()
{
InitializeComponent();
}
box s2 = new box();
class box
{
protected string fname;
protected string lname;
public void name(string s1, string s2)
{
fname = s1;
lname = s2;
}
}
void func(string x, string y)
{
s2.name(x, y);
}
private void btnClick_Click(object sender, EventArgs e)
{
string first = txtFname.Text;
string last = txtLname.Text;
func(first, last);
strQry = "Insert Into Practice Values(" + first + "," + last + " )";
cmd = new SqlCommand(strQry, con);
cmd.Connection.Open();
rowsaffected = cmd.ExecuteNonQuery();
cmd.Connection.Close();
MessageBox.Show(+rowsaffected + " row(s) affected");
}
private void Form1_Load(object sender, EventArgs e)
{
strCon = " Data Source = (local); Initial Catalog = Student; User Id= sa; Password=sa;";
con = new SqlConnection(strCon);
}
alt text http://img682.imageshack.us/img682/6017/hjki.jpg
sorry i didnt mention initialize it u mean to say con = new SqlConnection(strCon); i have done dat in dat case error is {"The name 'xyz' is not permitted in this context. Only constants, expressions, or variables allowed here. Column names are not permitted."}
You are not instantiating the con variable, for example:
SqlConnection con = new SqlConnection(connectionString);
I suppose the error happens because you use con, that is not initialized.
I don't see a SqlConnection con = new SqlConnection(strCon);
I bet your problem is with the connection string, and the connection object is null. Here is a quick way to generate and test a connection string:
Right click the windows desktop or inside a folder in windows explorer,
Click New -> Text Document
Rename the new file to Test.udl (.udl stands for Universal Data Link)
Create and test your connection with the UDL Dialog and click OK
Rename Test.udl to Test.txt and open the text file.
The text file will have a valid connection string that you can use in your code.
Also for your reference, I have simplified your code. The following should be much easier to debug:
private const string dbConnection = "USE THE UDL STRING HERE";
private void btnClick_Click(object sender, EventArgs e)
{
string first = txtFname.Text;
string last = txtLname.Text;
//I think the orig code was missing the single quotes
string query = string.Format("INSERT INTO Practice ('{0}','{1}')", first, last);
int rowsAffected = 0;
//Using statement will automatically close the connection for you
//Using a const for connection string ensures .NET Connection Pooling
using (SqlConnection conn = new SqlConnection(dbConnection))
{
//Creates a command associated with the SqlConnection
SqlCommand cmd = conn.CreateCommand();
//Set your sql statement
cmd.CommandText = query;
//open the connection
cmd.Connection.Open();
//Execute the connection
rowsAffected = cmd.ExecuteNonQuery();
}
MessageBox.Show(rowsAffected + " rows Affected");
}
Are you setting a connection string? It appears you are accessing the Connection object without telling it where to insert the data.
cmd.Connection.ConnectionString = "some string";
I don't think you need cmd.Connection.Open and cmd.Connection.Close.
cmd will open the connection & close it, in order to execute the query/stored procedure.
You are actually creating you connection correctly. What is happening is if you look at your connection string
strCon = " Data Source = (local); Initial Catalog = Student; User Id= sa; Password=sa;";
when it tries to connect it reads this as:
Data Source: " (local)"
Initial Catalog: " Student"
User Id= " sa"
Password - "sa"
So the spaces that you have after the equals signs are getting passed to the SQL server. What your string should look like is this
strCon = "Data Source =(local); Initial Catalog=Student;User Id=sa;Password=sa;"
I am pretty sure that you are never getting an actual connection to your database, but it's failing silently.
Any time you get a null reference on a line that has multiple calls linked together like:
something.somethingElse.somethingElse
break it apart and check each piece. For example, in your case this code:
cmd = new SqlCommand(strQry, con);
SqlConnection sc = cmd.Connection;
System.Diagnostics.Debug.Assert(sc != null, "You got a null connection from the SqlCommand.");
sc.Open();
may demonstrate what the problem is.