How to get fields from database [closed] - c#

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I want to get "Model" field and put on Textbox6. But how come it does not work.
The problem is that the Model field answer will not be shown in the textbox6
string Query = "Select * from S where Name = '" + TextBox1.Text + "' and Clientno = '" + TextBox2.Text + "';";
command.CommandText = Query;
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
string Model = reader.GetString(reader.GetOrdinal("Model"));
TextBox6.Text = Model;
}

Couple of things:
Do not use select *, instead use select your columns names
Do not pass the .Text directly to your query, instead use parameterized sql expression
If Clientno is primary key column or , combination of Name and ClientNo gives unique result, use ExecuteScalar, you don't have to use ExecuteReader and loop through the datareader
Since you using only one field and want to fill in the textbox, modify your select statement to :
select top 1 Model from S where....
And if you are reading only one row you will not need a while loop. Further, you should always close the reader and put your SqlConnection inside using block. ( edited as suggested by the comments)
If (reader.Read())
{
TextBox6.Text = reader.GetString(reader.GetOrdinal("Model"));
reader.Close();
}

Related

changed value on insert into table [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
can someone tell me why when I insert into database this string 01-02-20070858430013, the result is -20070858430014
using (SqlConnection connection = new SqlConnection(con1))
{
connection.Open();
for (int i = 0; i <= lb_dadosbrutos.Items.Count; i++)
{
using (SqlCommand command = new SqlCommand("INSERT INTO dbo.dados(Dados) VALUES(" + lb_dadosbrutos.Items[i] + ")", connection))
{
//MessageBox.Show("INSERT INTO dbo.dados (Dados) VALUES (01-02-20070858430013)");// + range.Cells[i, 1].Value2.ToString() + ")");
command.ExecuteNonQuery();
}
}
}
sry first stack question
Edit:
Tnks all, yes i missing the ' ', omg
I think you are trying to store this value as a string but your code is storing as integer.
so your query is suppose to have this following query with this 01-02-20070858430013 quoted in a string before been placed in a values.
("INSERT INTO dbo.dados (Dados) VALUES ('01-02-20070858430013')")
Check you Table design.
You may set column type as Int.Change it to nvarchar

MySQL Query Returns Parameter Column Name [duplicate]

This question already has answers here:
How to pass a table as parameter to MySqlCommand?
(2 answers)
Closed 6 years ago.
I am working in C# and MySQl in VS2015 to query my database and return a the information in a VARCHAR type column titled "method". However, the query returns the string "method", and not the values of the method column.
below is the code:
string queryOne = "SELECT " + "#columnName" + " FROM log.transactions";
MySqlCommand cmdOne = new MySqlCommand(queryOne, connectionString);
cmdOne.Parameters.AddWithValue("#columnName", "method");
MySqlDataReader dataReaderOne = cmdOne.ExecuteReader();
while (dataReaderOne.Read())
{
Console.WriteLine(dataReaderOne.GetString(0));
}
dataReaderOne.Close();
While this is the output:
method
method
method
.
.
.
.. for the number of rows in the method column. Is this a formatting problem? Is it possible that the configuration of my database is preventing VarChar's from returning correctly? When I change the query to query a column of type INT, it returns the correct values for an INT type column.
You can't parameterize a column name in a select statment. What you're doing is exaclty like saying select 'foo' from log.transactions. It selects the string 'foo' once for each row. You're just sticking a string value in there; it's not parsing the string value as SQL.
What you can do (if you can afford it) is select * from log.transactions, then your C# code can grab the data in whatever column the caller passed you the name of. With a lot of rows you could be dragging a lot of useless junk back from the DB though.
What you want in the code you show, though is just this:
string queryOne = "SELECT method FROM log.transactions";
If you really want to parameterize "method", that's sketchy because of SQL injection vulnerabilities.
string queryOne = "SELECT " + fieldname + " FROM log.transactions";
That looks good until some comedian using your application gives you a value of "0; drop table log.transactions;--" in the textbox. Then you've got troubles. If you ever concatenate a string variable into a SQL string that you're going to execute, you've got to be fanatical about sanitizing it, and even then you want to avoid it any way you can. It's Russian roulette.
Your query formation has to be like if you want to keep your column dynamic.Now pass column name accordingly.
string queryOne = "SELECT " + column_name + " FROM log.transactions";
MySqlCommand cmdOne = new MySqlCommand(queryOne, connectionString);
MySqlDataReader dataReaderOne = cmdOne.ExecuteReader();
while (dataReaderOne.Read())
{
Console.WriteLine(dataReaderOne[column_name]);
}
dataReaderOne.Close();

Select column values not existing in string array [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm writing a code in Asp.net c# to select some values from SQL Server database.
I want to get all the values in a table that does not contain the items of a string array.
In detail, I have a table named Notifications which contains 2 columns, 'Text' and 'Date'. I also have a string array.
I want to get all the Texts and dates that do not exist in my string array
Thank U all
You'll first need to convert your array of strings into a comma-separated list that can be passed into your query. Then have your query filter our any records where the value of the Text column is in that list:
public string GetNotifications(string[] texts)
{
// Create a single string with all values from the texts array.
// Ex: 'value1','value2','value3'
// There are many ways to do this; here's one way using string.Join and LINQ:
var textsAsSingleString = string.Join(",", texts
.Select(x => "'" + x.Replace("'", "''") + "'")
.ToArray());
// Create your query with a WHERE clause that checks against your list
var query = "SELECT Text, Date " +
"FROM Notifications " +
"WHERE Text NOT IN (" + textsAsSingleString + ")";
// Execute the query
SqlCommand cmd = new SqlCommand(query, con);
...
}
Now, this should work fine with a few values in the texts array, but if that array gets very large (how large depends on many environmental factors), the performance could start to degrade. However, unless you tell me otherwise, I'll assume the list isn't very long.
Edit: If any string in texts contains a single quote, this will fail. You need to replace any single single quote with two single quotes. I've updated the sample above to do this by calling Replace("'", "''") on each string in texts before adding it to the comma-separated list/string.
I am not sure what way you are connecting to DB but you can always use this:
If using Linq:
string sParms = String.Join(",", saParams.Select(str => "'" + str + "'").ToArray());
and then you can use sParms in your where clause.
If not using Linq:
string[] saParams = new string[3] { "String1", "String2", "String3" };
StringBuilder sbParams = new StringBuilder();
foreach(string sStr in saParams)
{
if (sbParams.Length > 0)
sbParams.Append(",");
sbParams.Append("'" + sStr + "'");
}
and then you can use sbParams.ToString() in your where clause.

Connecting to database [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I'm getting a run time error in my program when connecting to a SQL Server CE database.
Can anyone help me, and please don't write the whole code just a line of what needs to be changed to.
Here is my code:
string conString = Properties.Settings.Default.POSdatabaseConnectionString;
using (SqlCeConnection con = new SqlCeConnection(conString))
{
con.Open();
using (SqlCeCommand com = new SqlCeCommand("SELECT * FROM Customer where Customer ID ='" + this.useridtexbox.Text + "' and Name='" + this.nametexbox.Text + "'", con))
{
SqlCeDataReader reader = com.ExecuteReader();
int count = 0;
while (reader.Read())
{
count = count + 1;
}
if (count == 1)
{
MessageBox.Show("You have logged in succesfully");
Homepage homepage = new Homepage();
homepage.Show();
homepage.LabelText = ("Welcome " + reader["name"].ToString());
}
else
{
MessageBox.Show("Username and password is Not correct ...Please try again");
con.Close();
}
Error:
There was an error parsing the query. [ Token line number = 1,Token line offset = 39,Token in error = ID ]
I think the problem with the space in Customer ID,Try this
SqlCeCommand com = new SqlCeCommand("SELECT * FROM Customer where CustomerID ='" + this.useridtexbox.Text + "' and Name='" + this.nametexbox.Text + "'", con))
In your command, do not use string concatenation. That will fail badly and leave you open to SQL injection attacks.
Image what happens if I enter the following text into this.nametexbox.Text:
Joe'; DROP DATABASE; --
You don't want have someone like little Bobby Tables as user.
Use sql parameters.
If you have tables or fields with spaces, you to have a word with your DBA. If you cannot change it, make sure you use the correct syntax:
WHERE [Customer ID] = '12345'
Make sure you CustomerID column have space
Always use parameterized query to avoid SQL Injection
How does SQLParameter prevent SQL Injection
SqlCeCommand com = new SqlCeCommand = "SELECT * FROM Customer where CustomerID=#CustomerID and
name=#name";
con.Parameters.AddWithValue("#CustomerID", valuesTextBox.Text);
con.Parameters.AddWithValue("#name", namwTextBox.Text);

Select First table data and pass it to int value and print it in second table? ERRORS [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I want to select id from one table and insert that id to another table.
First I need to read my first table id and want to pass it to string.
Then I need to pass that string to second table.
String selQuery = "SELECT Id FROM MapDataImage WHERE Source='" + TextBox1.Text + "';";
{
int MId = int.TryParse(Id);
String QueryStr = "INSERT INTO User_Images VALUES (#Image)";
SqlCommand scmd = new SqlCommand(QueryStr, conn);
SqlDataReader sqldread = scmd.ExecuteReader();
//String QueryStr = "UPDATE MapDataImage SET Image = #Image WHERE Source='" + TextBox1.Text + "';";
//SqlCommand scmd = new SqlCommand(QueryStr, conn);
scmd.Parameters.Add("#Image", SqlDbType.VarBinary).Value = imgbytes;
scmd.ExecuteNonQuery();
}
so is this correct?
int MId = int.TryParse(Id); //the name id does not exist in current context?
but i want to retrieve particular id value from database
or
int MId = int.TryParse(#Id);
int MId = int.Parse("Id");
Will never work. "Id" is a string literal, it can never be an integer. I think you need to specify a variable
int mId = int.Parse(id);
Aside that, try using TryParse so it's safer.
Also use paramerterised queries on your SELECT statement to prevent SQL Injection.
Please post the rest of your code and I will adjust my answer to accomodate.
You don't create DataReaders objects by yourself. Instead you obtain a reference to DataReader object by invoking ExecuteReader method of Command class.
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executereader.aspx

Categories

Resources