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.
Related
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.
private void button1_Click(object sender, EventArgs e)
{
string usernames = textBox1.Text;
string passwords = textBox2.Text;
string emailid = textBox5.Text;
string telno = textBox6.Text;
string connectionstring = "Data Source=|DataDirectory|\\libdb.sdf; Persist Security Info=False ;";
using (SqlCeConnection con = new SqlCeConnection(connectionstring))
{
con.Open();
using (SqlCeCommand Query = new SqlCeCommand("INSERT INTO Registers " + "(usernames,passwords,emailid,telno) " + "VALUES (#usernames,#passwords,#emailid,#telno)", con))
{
Query.Parameters.AddWithValue("#usernames", usernames);
Query.Parameters.AddWithValue("#passwords", passwords);
Query.Parameters.AddWithValue("#emailid", emailid);
Query.Parameters.AddWithValue("#telno", telno);
Query.ExecuteNonQuery();
}
MessageBox.Show("QueryExecuted");
con.Close();
MessageBox.Show("Closedconnecrion");
con.Dispose();
MessageBox.Show("disposed");
this.Close();
/*string conString = "Data Source=" +
Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),
"MyAppData\\database.sdf") + ";Password=yourPassword;";
even this method dosent works */
}
}
}
on executing this code I find it executes successfully. But when I go and check the database, I find the entries empty...
I even tried refreshing database..
I didn't find problem in connectivity.
Query no error executed successfully.
The problem is I didn't find result or the data I gave as input in database.
Please be descriptive with code eg and mail to scarlet.gabriel#gmail.com
Test your connection with the database first, You can get the connection string by creating the udl file.
create a textfile and savaas it with the extension udl (example connection.udl).
double click and run this file.
a window will be opened where you can get the option for getting the connection string.
after testing the connection, close this window and open this file with a note pad.
copy the connection string and paste it in the below statement.
string connectionstring =" paste here";
How can you be sure if the connection is open and has done the job? Use try... catch block to catch if any error occurs:
using (SqlCeConnection con = new SqlCeConnection(connectionstring))
{
try{con.Open();}
catch(Exception ex)
{
// database connection error. log/display ex. > return.
}
if(con.State==ConnectionState.Open)
{
using (SqlCeCommand Query = new SqlCeCommand("INSERT INTO Registers " + "(usernames,passwords,emailid,telno) " + "VALUES (#usernames,#passwords,#emailid,#telno)", con))
{
Query.Parameters.AddWithValue("#usernames", usernames);
Query.Parameters.AddWithValue("#passwords", passwords);
Query.Parameters.AddWithValue("#emailid", emailid);
Query.Parameters.AddWithValue("#telno", telno);
try{
Query.ExecuteNonQuery();
}
catch(Exception ex)
{
// database communication error. log/display ex
}
}
MessageBox.Show("QueryExecuted");
}
if(con.State==ConnectionState.Open)
{
try{con.Close();}
catch{}
}
}
Instead of using connectionstring = "Data Source=|DataDirectory|\libdb.sdf; Persist Security Info=False ;"; Please try to use absolute path like
connectionstring = "Data Source=C:\Users\chandra\Documents\Visual Studio 2010\Projects\Window\LMS\AppData\LMSDatabase.sdf;Persist Security Info=False;";
I hope this will work.
Thanks
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 have a database that contains a table named "User(login,password,firstname,lastname)" . And I need to make login page . I've watched some tutorials , but it didn't help . I need to check if login and password exist in the database . and then redirect(if correct) to other page . This is what I already did:
OleDbConnection con = new OleDbConnection();
public bool check()
{
con.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Volodia\Documents\WebSiteDatabase.accdb";
con.Open();
string commandstring = "SELECT login,password FROM User";
//objadapter = new SqlDataAdapter(CommandString, sqlconn.ConnectionString);
OleDbDataAdapter objadapter = new OleDbDataAdapter(commandstring, con.ConnectionString);
DataSet dataset = new DataSet();
objadapter.Fill(dataset, "User");// it shows "Syntax error in FROM clause." here
DataTable datatable = dataset.Tables[0];
for (int i = 0; i < datatable.Rows.Count; i++)
{
string unam = datatable.Rows[i]["login"].ToString();
string upwd = datatable.Rows[i]["password"].ToString();
if ((unam == TextBox1.Text)&&(upwd==TextBox2.Text))
{
return true;
}
}
return false;
}
protected void Button1_Click(object sender, EventArgs e)
{
if (check() == true)
{
Response.Redirect("WebForm2.aspx");
}
}
The word PASSWORD is a reserved keyword for MS-Access Jet SQL. If you want to use it you need to enclose it in square brackets, the same for USER
string commandstring = "SELECT login, [password] FROM [User]";
This will resolve the immediate problem of the Syntax Error but let me add some other code to show a different approach
public bool check()
{
string conString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Volodia\Documents\WebSiteDatabase.accdb";
using(OleDbConnection con = new OleDbConnection(conString)
{
con.Open();
string commandstring = "SELECT count(*) as cntUser FROM [User] " +
"WHERE login = ? AND [password] = ?";
using(OleDbCommand cmd = new OleDbCommand(commandstring, con))
{
cmd.Parameters.AddWithValue("#p1", TextBox1.Text);
cmd.Parameters.AddWithValue("#p2", TextBox2.Text);
int result = (int)cmd.ExecuteScalar();
if(result > 0)
return true;
}
}
return false;
}
First, do not use a global connection object but create and use the
connection only when needed.
Second, encapsulate the disposable objects like the connection and
the command with the using statement that will ensure a correct close
and dispose,
Third, pass the login and the password as conditions for the where
clause (more on this later)
Fourth, use the parametrized query to avoid syntax errors and sql
injection
Usually is not a good practice to store a password in clear text inside the database. You need to store only the hash of the password and recalculate this hash every time you need to check the user authenticity
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.