Recycling Connection String In Windows Forms C# - c#

I'm trying to reuse a connection string created from a DataGridView. I can't seem to translate the value in the Settings.settings file to a usable connection string. Any ideas of what the Connection_String SHOULD look like?
Error:
Format of the initialization string does not conform to specification starting at index 0.
Code:
// This fills the gridview
this.loanacctTableAdapter.FillBy(this.innovate_Loan_ServicingDataSet.loanacct, ((decimal)(System.Convert.ChangeType(acctrefnoToolStripTextBox.Text, typeof(decimal)))));
// This tries to use the same connection
Connection_String = SpecialSetting.ConnectionString.ToString();
Command = "SELECT acctrefno FROM loanacct WHERE acctrefno = " + AcctrefnoToolStripTextBox.Text + "";
SqlConnection Conn = new SqlConnection(Connection_String);
SqlCommand Comm1 = new SqlCommand(Command, Conn);
Conn.Open();
SqlDataReader DR1 = Comm1.ExecuteReader();
if (DR1.Read())
{
textBox1.Text = DR1.GetValue(0).ToString();
textBox1.ReadOnly = true;
}
Conn.Close();
Settings.Designer.cs
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.SpecialSettingAttribute(global::System.Configuration.SpecialSetting.ConnectionString)]
[global::System.Configuration.DefaultSettingValueAttribute("Data Source=ILSVUPGRADE01;Initial Catalog=Innovate_Loan_Servicing;Integrated Secu" +
"rity=True")]
public string Innovate_Loan_ServicingConnectionString {
get {
return ((string)(this["Innovate_Loan_ServicingConnectionString"]));

ConnectionString is simply a String. I suggest to use the SqlConnectionStringBuilder Class. It makes it much easier to create a valid connection string.
You can get the full ConnectionString then with .ToString()

The solution ended up being the difference between Windows Forms and ASP.NET. I needed to find the configuration in the Settings.settings file and drill down. Windows forms stores the connection string as "Properties.Settings.Default. name of connection here.ToString(); The command and connection can then be set simply. ASP.NET sets the connection string under ConfigurationSettings.AppSettings("myConnectionString").
My code ended up looking like this.
string Connection_String = Properties.Settings.Default.Innovate_Loan_ServicingConnectionString.ToString();
string Command = "SELECT acctrefno, loan_number, [shortname], [loan_group_no] FROM loanacct WHERE acctrefno = " + acctrefnoToolStripTextBox.Text + "";
SqlConnection Conn = new SqlConnection(Connection_String);
SqlCommand Comm1 = new SqlCommand(Command, Conn);
Conn.Open();
SqlDataReader DR1 = Comm1.ExecuteReader();
if (DR1.Read())
etc.

Related

can't read int value from sql database

I have tried this code in C#, and it's not working - I can't get an input id, every time I run it, the value of id is 0.
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=sms;Persist Security Info=True;User ID=boy;Password=coco");
int id;
con.Open();
string sql = "select * from Staff_Management where Emp_Name = '"+sName+"'; ";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader read = cmd.ExecuteReader();
if (read.Read())
{
id = read.GetInt32(0);
TM_AC_SelectId.Text = id.ToString();
}
else
{
MessageBox.Show("Error 009 ");
}
con.Close();
You should try to follow the accepted best practices for ADO.NET programming:
use parameters for your query - always - no exceptions
use the using(...) { .... } construct to ensure proper and quick disposal of your resources
select really only those columns that you need - don't just use SELECT * out of lazyness - specify your columns that you really need!
Change your code to this:
// define connection string (typically loaded from config) and query as strings
string connString = "Data Source=.;Initial Catalog=sms;Persist Security Info=True;User ID=boy;Password=coco";
string query = "SELECT id FROM dbo.Staff_Management WHERE Emp_Name = #EmpName;";
// define SQL connection and command in "using" blocks
using (SqlConnection con = new SqlConnection(connString))
using (SqlCommand cmd = new SqlCommand(query, con))
{
// set the parameter value
cmd.Parameter.Add("#EmpName", SqlDbType.VarChar, 100).Value = sName;
// open connection, execute scalar, close connection
con.Open();
object result = cmd.ExecuteScalar();
con.Close();
int id;
if(result != null)
{
if (int.TryParse(result.ToString(), out id)
{
// do whatever when the "id" is properly found
}
}
}

C# Write sql query to file?

I want to write an sql query to a file, but I'm only able to write one column of the query inside the text file. How do I add more columns ?
This is my c# windows form code:
SqlConnection con = new SqlConnection(#"Data Source=" + globalvariables.hosttxt + "," + globalvariables.porttxt + "\\SQLEXPRESS;Database=ha;Persist Security Info=false; UID='" + globalvariables.user + "' ; PWD='" + globalvariables.psw + "'");
SqlCommand command = con.CreateCommand();
command.CommandText = "Select * from bestillinger";
con.Open();
SqlDataReader queryReader = command.ExecuteReader();
while (queryReader.Read())
{
StreamWriter file = new StreamWriter(#"C:\Users\Michael\Desktop\query.txt");
file.WriteLine(queryReader["ordrenr"]);
file.Close();
}
queryReader.Close();
con.Close();
It wont allow me to write:
file.WriteLine(queryReader["ordrenr"] + queryReader["user"]);
I realize this six years old now, but seeing as I came across this in my own searching, I felt that offering a slightly cleaner answer would be good for others, as well. Also, I can't make comments yet, so I thought I might as well submit this as an answer.
The OP's answer presents a pretty major performance issue with recreating the stream with every row, as pointed out by Magus in the comments.
Meanwhile, mybirthname's answer actually never ends up adding a header row, and if the bool included is changed to true upon creation, it'll end up making a file filled with nothing but headers.
In this particular case, I'm writing the data out in a Comma Separated Value format. The file extension can be .csv if you want to open this in a spreadsheet editor afterwards, or .txt if it's not meant to be viewed by any end user.
//Consider putting your connection string in a config file and referencing it here.
SqlConnection sqlConn = new SqlConnection(Properties.Settings.Default.ConnString);
//If possible, avoid using "Select *" and instead, select only the columns you care about to increase efficiency.
SqlCommand sqlCmd = new SqlCommand("Select ordrenr, user From bestillinger", sqlConn);
sqlConn.Open();
SqlDataReader sdr = sqlCmd.ExecuteReader();
if (sdr.HasRows)
{
//There's really no reason to create the StreamWriter unless you actually find some data.
StreamWriter swExportWriter = new StreamWriter(#"C:\DataStore\Datafile.csv");
//Now that you know you have data, go ahead and write the first line to the file as the header row.
swExportWriter.WriteLine("ordrenr, user");
//Now use SqlDataReader.Read() to loop through the records and write each one to the file.
while (sdr.Read())
{
swExportWriter.WriteLine("{0},{1}", sdr["ordrenr"], sdr["user"]);
}
//Don't forget to close the StreamWriter!
swExportWriter.Close();
}
sdr.Close();
sqlConn.Close();
If you'd like to use Using statements instead, as per Magus' suggestion (which is probably a good idea), you can also structure it like so:
using (SqlConnection sqlConn = new SqlConnection(Properties.Settings.Default.ConnString))
{
SqlCommand sqlCmd = new SqlCommand("Select ordrenr, user From bestillinger", sqlConn)
sqlConn.Open();
using (SqlDataReader sdr = sqlCmd.ExecuteReader())
{
if (sdr.HasRows)
{
using (StreamWriter swExportWriter = new StreamWriter(#"C:\DataStore\Datafile.csv"))
{
swExportWriter.WriteLine("ordrenr, user");
while (sdr.Read())
{
swExportWriter.WriteLine("{0},{1}", sdr["ordrenr"], sdr["user"]);
}
}
}
}
}
I found a way:
file.WriteLine("{0},{1}", queryReader["ordrenr"], queryReader["user"]);
static void Main(string[] args)
{
string connString = #"here connection string";
SqlConnection con = new SqlConnection(connString);
SqlCommand command = con.CreateCommand();
command.CommandText = "Select * from Object";
con.Open();
SqlDataReader queryReader = command.ExecuteReader();
StreamWriter file = new StreamWriter(#"C:\Projects\EverydayProject\test.txt");
bool addColumns = false;
string columnName1="Title";
string columnName2 = "City";
while (queryReader.Read())
{
if(addColumns)
{
file.WriteLine(columnName1 + " " + columnName2);
addColumns = true;
}
else
{
file.WriteLine(queryReader["Title"].ToString() + " " + queryReader["City"].ToString());
}
}
queryReader.Close();
con.Close();
file.Close();
}
This is working you should first make the objects to String() also you need to close the file at the end. Not on first iteration !

Error binding in GetColumnNumber at row 1

I got this OfficeWriter error when debugging the console application. I used methods to retrieve config details for the database used in the coding from the master database, and ended up having this error.
Error binding in GetColumnNumber at row 1
Attached here is partial coding for my work. Anyone can explain me what the error is?
SqlDataReader rdSource = getSource();
SqlDataReader rdDestination = getDestination();
SqlDataReader rdCode = getCode();
while (rdSource.Read() && rdDestination.Read())
{
string src = rdSource["Value"].ToString();
string dest = rdDest["Value"].ToString();
ExcelTemplate XLT = new ExcelTemplate();
XLT.Open(src);
DataBindingProperties dataProps = XLT.CreateBindingProperties();
XLT.BindData(rdCode, "Code", dataProps);
XLT.Process();
XLT.Save(dest);
}
//rdCode method
SqlDataReader rdConnection = getConnection(); //method for getting connection from master
while (rdConnection.Read())
{
string con = rdConnection["Value"].ToString();
SqlConnection sqlCon = new SqlConnection(con);
string SQL = "SELECT * FROM Sales.Currency";
sqlCon.Open();
SqlCommand cmd = new SqlCommand(SQL, sqlCon);
cmd.ExecuteReader();
sqlCon.Close();
}
return rdConnection;
//getConnection method
string strCon = ConfigurationManager.ConnectionStrings["Master"].ConnectionString;
SqlConnection sqlCon = new SqlConnection(strCon);
string cSQL = "SELECT Value FROM dbo.COMMON_CONFIG WHERE Value = 'Data Source=localhost;Initial Catalog=Test;Integrated Security=True'";
SqlCommand cmd = new SqlCommand(cSQL, sqlCon);
sqlCon.Open();
return new SqlCommand(cSQL, sqlCon).ExecuteReader(CommandBehavior.ConnectionString);
//getSource & getDestination methods
string strCon = ConfigurationManager.ConnectionStrings["Master"].ConnectionString;
SqlConnection sqlCon = new SqlConnection(strCon);
string srcPath = #"FILE PATH NAME"; //change to destPath for getDestination
string sSQL = "SELECT Value FROM dbo.COMMON_CONFIG WHERE Value = '" + srcPath + "'";
SqlCommand cmd = new SqlCommand(cSQL, sqlCon);
sqlCon.Open();
return new SqlCommand(cSQL, sqlCon).ExecuteReader(CommandBehavior.ConnectionString);
The error is a generic message that is thrown by ExcelWriter when it is unable to bind data to the template.
I think this might be caused by your getCode() method. In getCode(), you use a SQLDataReader to retrieve the connection string for the database:
SqlDataReader rdConnection = getConnection(); //method for getting connection from master
Then you execute a SQL query against that database, but you don't actually get a handle on the SqlDataReader that is executing the SQL query to return the data.
SqlCommand cmd = new SqlCommand(SQL, sqlCon);
cmd.ExecuteReader(); //Note: This returns the SqlDataReader that contains the data
Then you return rdConnection, which is the SQLDataReader for the connection string - not the data you are trying to import. rdConnection contained 1 row and you already called Read(), so there are no records left to read.
SqlDataReader rdCode = getCode();
...
XLT.BindData(rdCode, "Code", dataProps);
The SQL reader you are binding is the used 'connection string', rather than your sales data. I would recommend the following:
Return the new SqlDataReader that is generated by cmd.ExecuteReader() in getCode(), rather than rdConnection.
Do not close the connection to this new SqlDataReader. ExcelWriter needs to be able to read the data reader in order to bind the data. If you close the connection, ExcelWriter will not be able to bind data correctly.

Getting Error while trying to update record in Ms Access 2007 using c#

Trying update record dont know why i am getting error
Exception Details: System.Data.OleDb.OleDbException: No value given for one or more required parameters.
this is my code please guide me.
public static string lasttable;
public static string newtable;
newtable = "c" + cont.ToString();
lasttable = input;
string connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\AGENTJ.AGENTJ-PC\Documents\Visual Studio 2010\WebSites\mfaridalam\App_Data\mfaridalam1.accdb; Persist Security Info=False;";
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
string query = "UPDATE [LastInfo] SET [LastAlbum]=#newtable WHERE [LastAlbum]=#lasttable";
OleDbCommand comd = new OleDbCommand();
comd.Parameters.Add("#LastAlbum", OleDbType.VarChar);
comd.Parameters["#LastAlbum"].Value = newtable;
comd.CommandText = query;
comd.Connection = conn;
comd.ExecuteNonQuery();
conn.Close();
You are using OleDb and OleDb doesn't care about parameter names.
However you need to add a parameter for every placeholder present in the command text and in the same order in which they appear.
You have two parameter (#newtable and #lasttable) but you add just one parameter (and you name it wrongly, but, as I have said, that doesn't matter for OleDb).
You need to add the second parameter #lasttable
string connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\AGENTJ.AGENTJ-PC\Documents\Visual Studio 2010\WebSites\mfaridalam\App_Data\mfaridalam1.accdb; Persist Security Info=False;";
using(OleDbConnection conn = new OleDbConnection(connectionString))
{
conn.Open();
string query = "UPDATE [LastInfo] SET [LastAlbum]=#newtable WHERE [LastAlbum]=#lasttable";
OleDbCommand comd = new OleDbCommand();
comd.Parameters.Add("#newTable", OleDbType.VarChar);
comd.Parameters["#newTable"].Value = newtable;
comd.Parameters.Add("#lastTable", OleDbType.VarChar);
comd.Parameters["#lastTable"].Value = lasttable;
comd.CommandText = query;
comd.Connection = conn;
comd.ExecuteNonQuery();
}

"Use of unassigned variable" error

I am developing this website in ASP.NET and using C#. I am Getting the error that :Use of unassigned variable usn. The database is also not empty.
My code is:
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection();
SqlCommand cm = new SqlCommand();
SqlDataReader dr;
cn.ConnectionString = #"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Vijaylaxmi\Desktop\TrainReserveold\App_Data\Database.mdf;Integrated Security=True;User Instance=True";
cn.Open();
cm.Connection = cn;
String usn;
cm.CommandText = "Select UserName from User where UserName='" + TextBox1.Text + "'";
dr = cm.ExecuteReader();
while (dr.Read())
{
usn = dr.GetString(0);
}
if (String.Compare(usn, TextBox1.Text) != 0)
{
Response.Write("Invalid user name... try again");
TextBox1.Text = "";
TextBox2.Text = "";
TextBox1.Focus();
}
Response.Write("user valid now");
}
Several problems I see here. In specific response to your question, you want to replace this:
dr = cm.ExecuteReader();
while(dr.Read())
{
usn = dr.GetString(0);
}
with this:
usn = cm.ExecuteScalar().ToString();
Be sure to check for DBNull first, just in case.
More generally, you want to
a) Parameterize your SQL (or, better, use a stored proc) instead of using raw input. This will protect you from SQL Injection attacks.
b) Not include your connection string directly in code. Put it in a config file. Most certainly don't post it on the internet.
assing the usn string up top as
string usn = string.empty; then go from there
//create a Stored Procedure and put your Select Statement in there.. to avoid Sql Injection
cmd.CommandText = "name of your stored proc";
cmd.CommandType = System.Data.CommandType.StoredProcedure;
I would also read my sql connectiong string from a web.config or app.config depending on the type of application you are running.
change your cm.CommandText = "Select UserName from User where UserName=
to
cm.CommandText = string.Format("Select UserName from User where UserName= '{0}'",Textbox1.Text);

Categories