I am very new to c# and visual studios 2015 so any opinions are happily accepted(even bad ones).
Is there a way to directly pull out DateTime to a format of "ddd" using reader.read like for example:
textBox1.Text = Convert.ToDateTime(reader[1].ToString()).ToShortDateString();
I have a very basic grasp of DateTime to string but not sure if the it can be placed in reader.read or not.
My data table contents is this:
And my textBox1 shows this:
Trying to make that text box show "Thu" instead of the date from my code below:
if (btnSearch.Text == "Search")
{
string sqlStmt = #"SELECT * FROM dbo.tbl_employees WHERE emp_id = #emp_id;";
using (SqlConnection dbCon = new SqlConnection(conStr))
{
SqlCommand dbCmd = new SqlCommand(sqlStmt, dbCon);
dbCmd.Parameters.AddWithValue("#emp_id", txtSearchID.Text);
dbCon.Open();
SqlDataReader reader = dbCmd.ExecuteReader();
while (reader.Read())
{
textBox1.Text = Convert.ToDateTime(reader[1].ToString()).ToShortDateString();
}
reader.Close();
dbCon.Close();
}
}
Sql:
[day_received] Date NOT NULL,
Thanks.
Assuming that your reader object is of type MySqlDataReader, a modification of the following should work:
using(var reader = cmd.ExecuteReader()){
if(reader.Read())
textBox1.Text = reader.GetDateTime(fieldIndex)
.ToShortDateString();
}
using(var reader = cmd.ExecuteReader())
{
if(reader.Read())
{
/// Considering GetDateTime returns a DateTime object...
DateTime dtTemp = reader.GetDateTime(fieldIndex);
textBox1.Text = dtTemp.toString("dddd");
}
}
Is this what you are looking for?
Related
I am very new to database queries and even more so, Oracle. I am also new to development work and, believe it or not, am creating this an for work purely out of frustration with the current process. Anyway, I am attempting to collect input from a multi-line text box and run a query. Each line corresponds to a single string that needs to be passed into the WHERE statement and the results will be dumped into a data table. Unfortunately, Oracle has still not released its developer tools for VS2019 so I am having to do this the harder way.
UPDATE # 2:
I have completely rebuilt the query since it was not running even when using known working code from another query. Below is what I have pieced together from various places on the interwebs. While debugging, it appears to parse and format the text correctly and pass it into the OracleParameter without issue. I am getting a Missing Expression error but I don't know what I am missing.
var connString =
ConfigurationManager.ConnectionStrings["dB"].ConnectionString;
string query = "SELECT col1, col2, col3, col4 FROM table WHERE col5 IN (";
using (OracleConnection conn = new OracleConnection(connString))
try
{
var input = "";
input = uniLookup.UniList;
var uniList = string.Join(",", Regex.Split(input, #"(?:\r\n|\n|\r)"));
string allParams = uniList;
string formattedParams = allParams.Replace(" ", string.Empty);
string[] splitParams = formattedParams.Split(',');
List<OracleParameter> parameters = new List<OracleParameter>();
using (OracleCommand cmd = new OracleCommand(query, conn))
{
for (int i = 0; i < splitParams.Length; i++)
{
query += #":Uni" + i + ",";
parameters.Add(new OracleParameter(":Uni" + i, splitParams[i]));
{
query = query.Substring(0, (query.Length - 1));
query += ')';
conn.Open();
using (OracleDataReader reader = cmd.ExecuteReader()) <==ERROR
{
if (!reader.HasRows)
{
while (reader.Read())
{
reader.Read();
{
MessageBox.Show(reader.GetString(1));
}
}
}
You can use IN in your where clause in this way to get rows from multiple values as:
string query = "SELECT dummyCol FROM dummytable WHERE altCol IN ("+text+");";
where you just have to change your text as text="'value1','value2','value3'"; this will not produce any syntax error.
You can convert your multi line text into same comma separated values using this :
foreach (String s in textBox1.Text.Split('\n'))
{
text +="'"+ s+"',";
}
text = text.TrimEnd(',');
this will help you achieve what you need. you can ask If there is any confusion.
Your final code will become :
public void GetData()
{
if (string.IsNullOrWhiteSpace(textbox1.Text) || textbox1.Text == "")
{
MessageBox.Show("Please Enter at least 1 Value and Try Again!");
}
else
{
System.Data.DataTable dt = new System.Data.DataTable();
// string[] lines = textbox1.Text.Split('\n');
string text = "";
foreach (String s in textBox1.Text.Split('\n'))
{
text += "'" + s + "',";
}
text = text.TrimEnd(',');
//Connection Credentials
string credentials = "Credentials";
string query = "SELECT dummyCol FROM dummytable WHERE altCol IN ("+text+");";
OracleConnection conn = new OracleConnection(credentials);
try
{
//Open The Connection
conn.Open();
using (OracleCommand cmd = new OracleCommand(query, conn))
{
//Call the Oracle Reader
using (OracleDataReader reader = cmd.ExecuteReader())
{
if (!reader.HasRows)
{
MessageBox.Show("Unable to Retrieve Data");
return;
}
else if (reader.HasRows)
{
reader.Read();
DataRow row = dt.NewRow();
// create variables to accept reader data for each column
// insert data from query into each column here
dt.Rows.Add(row);
}
}
}
}
}
}
i am working on android client and .NET server application, in which i parse data into xml and then convert into string and then send this string to android client.now i am facing problem in getting data from SQL Server in xml format and convering it into string.here is my code..
UserLogin userLogin = converter.GetObjectFromXml<UserLogin>(xml);
String query = #"Select StdBD.First_NameEn As name from TblStudentBioData As StdBD Join TblStudentDetail As StdDet ON StdBD.Student_ID = StdDet.Student_ID
join TblClassSchedule As ClsSch on StdDet.ClassID = ClsSch.ClassSchID
join TblClass As Cls on ClsSch.ClassID = Cls.ClassID
join TblSemAssigning As SemAs on SemAs.SemAssId = ClsSch.SemAssId
join TblAcademicYear As Acd on SemAs.AcademicYearId = Acd.AcademicYearId
where Acd.AcademicYearId = " + userLogin.userId + "FOR XML RAW('Student'),Root('Students'),Elements";
String outputXml = General.ExecuteSimpleSelectQuery(General.connectionString, query, "Table user");
Console.WriteLine("xmllll = "+outputXml);
and
class General
{
public static String ServerIp = "192.168.1.2";
public static String ServerPort = "8060";
public static String connectionString = NetService2.Properties.Settings.Default.ConnString.ToString();
public static String ExecuteSimpleSelectQuery(string ConnectionString, string _Query, string DataTableName)
{
SqlConnection conn = new SqlConnection(ConnectionString);
SqlCommand cmd = new SqlCommand(_Query,conn);
SqlDataReader reader = null;
conn.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("name = " + reader[0].ToString());
}
reader.Close();
conn.Close();
return "";
}
Output:
by using this code i am getting data in SqlDataReader instance but not in string,so is there any way to directly get data into string or convert SqlDataReader instance data into string,so i can use it.
i want output like this:
String xml = "<Students>
<Student>
<name>Aliya</name>
</Student>
<Student>
<name>Fahad</name>
</Student>
<Student>
<name>iqra</name>
</Student>
<Student>
<name>iqra</name>
</Student>
<Student>
<name>khurram</name>
</Student>
<Student>
<name>Zainab</name>
</Student>
<Student>
<name>Fatima</name>
</Student>
<Student>
<name>Fahad</name>
</Student>
</Students>";
replace this hard coded xml to the xml, getting from database.
just get your XML data in a DataTable it will give you an xml at its first position and then convert it into an string.
SqlConnection conn = new SqlConnection(yourConnectionString);
SqlCommand cmd = new SqlCommand(your query,conn);
SqlDataAdapter SDA = new SqlDataAdapter();
DataTable dt = new DataTable(DataTableName);
conn.Open();
SDA.Fill(dt);
conn.Close();
String xml = dt.Rows[0].ItemArray[0].ToString();
return xml;
Simple put your query into storedprocedure
Create PROCEDURE yourprocedurename
AS
BEGIN
Select StdBD.First_NameEn As name from TblStudentBioData As StdBD
Join TblStudentDetail As StdDet ON StdBD.Student_ID = StdDet.Student_ID
join TblClassSchedule As ClsSch on StdDet.ClassID = ClsSch.ClassSchID
join TblClass As Cls on ClsSch.ClassID = Cls.ClassID
join TblSemAssigning As SemAs on SemAs.SemAssId = ClsSch.SemAssId
join TblAcademicYear As Acd on SemAs.AcademicYearId = Acd.AcademicYearId
where Acd.AcademicYearId = " + userLogin.userId + "FOR XML
RAW('Student'),Root('Students'),Elements";
END
and from coding side do something like this
public static String ExecuteSimpleSelectQuery(string ConnectionString,
string _Query, string DataTableName)
{
SqlConnection conn = new SqlConnection(ConnectionString);
SqlCommand cmd = new SqlCommand("yourstoredprocedurename",conn);
SqlDataAdapter SDA = new SqlDataAdapter();
DataTable dt = new DataTable(DataTableName);
conn.Open();
cmd.CommandType = CommandType.StoredProcedure;
SDA.SelectCommand = cmd;
SDA.Fill(dt);
conn.Close();
return dt.Rows[0].ItemArray[0].ToString();
}
hopefully it will give you the required output
You could use String.Join after you've loaded all records into a List<string>:
public static String ExecuteSimpleSelectQuery(string ConnectionString, string _Query, string DataTableName)
{
List<string> list = new List<string>();
using(SqlConnection conn = new SqlConnection(ConnectionString))
using (SqlCommand cmd = new SqlCommand(_Query, conn))
{
conn.Open();
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
list.Add("name = " + reader.GetString(0));
}
}
}
return string.Join(Environment.NewLine, list);
}
However, don't use string concatenation for your sql commands because you are vulnerable to sql-injection. So don't pass the query to the method ExecuteSimpleSelectQuery. Instead use sql-parameters.
Your function will always return empty string as you return "" after every time function is called. Try change your function as:
public static String ExecuteSimpleSelectQuery(string ConnectionString, string _Query, string DataTableName)
{
SqlConnection conn = new SqlConnection(ConnectionString);
SqlCommand cmd = new SqlCommand(_Query,conn);
string result;
conn.Open();
var dt = new DataTable();
dt.Load( cmd.ExecuteReader());
using (StringWriter sw = new StringWriter()) {
dt.WriteXml(sw);
result = sw.ToString();
}
conn.Close();
return result;
}
Yes, you can capture your column data into a string. By default, all of your data types will be considered an object. Which means you'll have to:
Use the SqlDataReader built in function.
Use the ToString()
Use a (string) or as string Cast.
Before I provide an example, something you should do before you attempt to work with the data, a null check.
if(reader[0] != DBNull.Value)
{
// Do Something...
}
The reason, is if you perform certain manipulations on the data you'll receive an Exception. Another useful thing, wouldn't be to use [0] but rather the ["NameOfColumn"] as later on maintaining the code, will make the specific data easier to read and see what it does.
if(reader["NameOfColumn"] != DBNull.Value)
example = reader["NameOfColumn"].ToString();
if(reader["NameOfColumn"] != DBNull.Value)
example = (string)reader["NameOfColumn"];
example = reader["NameOfColumn"] as string;
Those are some primitive examples, the last one if it fails will assign a null. So you'll want to anticipate that bubbling potentially in your code. The first example, is the most common and simple.
However, if you want to avoid repeating said code.
public static class DataReaderExtension
{
public static string GetStringOrNull(this IDataReader reader, int ordinal)
{
var value = null;
if(!reader.IsDBNull(reader.GetOrdinal(ordinal)
reader.GetString(ordinal);
return value;
}
public static string GetStringOrNull(this IDataReader reader, string columnName)
{
return reader.GetStringOrNull(reader.GetOrdinal(columnName));
}
}
Those are several different approaches. Hopefully that indeed helps you.
I'm using c# in a ASP.Net web application.I have the following query:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["chestionar"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select * from personal,Intrebari where personal.cod_numeric_personal=#cnp AND Intrebari.id_intrebare=14 AND Intrebari.id_intrebare=15 ", con);
cmd.Parameters.AddWithValue("#cnp", Session["sesiune_cnp"]);
SqlDataReader rdr;
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
lbl1.Text = rdr["Nume"].ToString();
intrebare6.Text = rdr["Intrebari"].ToString();
intrebare7.Text = rdr["Intrebari"].ToString();
}
I want those two values for id_intrebare=14 and 15 to assign it to those 2 labels.How can i refer to those?
In order to read stuff from the reader you need to include it in the select statement for you sql, it is better to select it explicitly rather than use select *.
but you are not currently going to get any results returned because id_intrebare cannot be both 14 and 15
you then need to read id_intreabare ratherr than Intreabari.
Try this, notice the try catch block, I also changed your SQL query.
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["chestionar"].ConnectionString);
string qry="select * from personal,Intrebari where personal.cod_numeric_personal=#cnp AND Intrebari.id_intrebare IN (14,15);
SqlCommand cmd = new SqlCommand(qry, con);
cmd.Parameters.AddWithValue("#cnp", Session["sesiune_cnp"]);
try
{
con.Open();
SqlDataReader rdr= cmd.ExecuteReader();
if(rdr.HasRows)
{
while (rdr.Read())
{
lbl1.Text = rdr["Nume"].ToString();
intrebare6.Text = rdr["Intrebari"].ToString();
intrebare7.Text = rdr["Intrebari"].ToString();
}
}
}
catch(SQLException ex)
{
lblStatus.Text="An error occured"+ex.Message;
throw ex;
}
finally
{
con.Close();
con.Dispose();
}
If you want to assign texts to different numbered lables in a loop, you can refer to the control id with FindControl of the current page
int numeOrdinal = reader.GetOrdinal("Nume");
int intrebariOrdinal = reader.GetOrdinal("Intrebari");
int i = 1;
while (rdr.Read()) {
// Nume (Romanian) = Name
page.FindControl("lbl" + i).Text = reader.IsDBNull(numeOrdinal)
? ""
: rdr.GetString(numeOrdinal);
// Intrebari (Romanian) = Question
page.FindControl("intrebari" + i + 5).Text = reader.IsDBNull(intrebariOrdinal)
? ""
: rdr.GetString(intrebariOrdinal);
i++;
}
Try using cmd.ExecuteScalar it will return the first reuslt it finds so you have to define your conditions well. Also it returns object type so you will have to cast the result
I want to find current day of week in c# ASP.Net like:
System.DateTime.Now.DayOfWeek.ToString();
This code works well in a console application, but when I try to store the value of this line in a string in ASP.Net website it returns nothing.
Can anyone help?
StringBuilder message = null;
protected void Page_Load(object sender, EventArgs e)
{
var dayofweek = System.DateTime.Now.DayOfWeek.ToString();
String conn = "Data Source=.;Initial Catalog=OCSI;Integrated Security=True";//conne
SqlConnection sqlconne = new SqlConnection(conn);
string selectSQL = "SELECT lec FROM schedule WHERE [day]='" + dayofweek +"'";
SqlCommand cmd = new SqlCommand(selectSQL, sqlconne);
SqlDataReader reader = null;
try
{
sqlconne.Open();
reader = cmd.ExecuteReader();
message = new StringBuider();
while (reader.Read())
{
message.Append(reader["lec"].ToString());
//question what are you using message for ...?
Label3.Text = dayofweek;
}
reader.Close();
}
catch (Exception ex)
{
Response.Write(ex.Mesage);
}
finally
{
sqlconne.Close();
// you neeed to Dispose of all other objects here too
// StringBuilder Object
// SqlDataReader Object
//SqlCommand Object..
//Look into wrapping your Connection / Command Sql Dataobject around a using() {}
}
I want to use current day in where clause SQL Query to get data relevant to current day from database table.
I used var as
protected void Page_Load(object sender, EventArgs e)
{
String conn = "Data Source=.;Initial Catalog=OCSI;Integrated Security=True";//conne
SqlConnection sqlconne = new SqlConnection(conn);
var testDay = DateTime.Now.DayOfWeek.ToString();
// string selectSQL = "SELECT lec FROM schedule WHERE [day]='" + dayofweek +"'";
string selectSQL = string.Format("SELECT lec FROM schedule WHERE [day]= {0}", testDay);
SqlCommand cmd = new SqlCommand(selectSQL, sqlconne);
SqlDataReader reader;
try
{
sqlconne.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
message += reader["lec"].ToString();
Label3.Text = testDay;
}
reader.Close();
}
catch
{
}
finally
{
sqlconne.Close();
}
It works fine for me.
Wep page is the value defined as a public , static, or property..
if you write
var testDay = DateTime.Now.DayOfWeek.ToString();
the results will = "Friday";
if everything is working fine when you remove the where clause then change the Where clause to be something like this
string selectSQL = string.Format("SELECT lec FROM schedule WHERE dbo.schedule.day = {0} ", testDay);
I would also change the name of the field day to something like DayName or something if day is a Reserved word don't use it..
look at this link for Reserved Words in SQL Reserved SQL Words
Also try changing your sql string to this
string selectSQL =
string.Format("SELECT lec FROM schedule WHERE [day]= {0}", dayofweek);
As an integer value (system sets sunday's as 0) =
int day = (int)DateTime.Now.DayOfWeek;
Hello I'm in need of a code to read columns and rows for C#.
I've come this far:
obj.MysqlQUERY("SELECT * FROM `players` WHERE name = "+name+";"); // my query function
Grateful for help;]
Here is a standard block of code that I use with MySql a lot. Note that you must be using the MySql connector available here.
string myName = "Foo Bar";
using (MySqlConnection conn = new MySqlConnection("your connection string here"))
{
using (MySqlCommand cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = #"SELECT * FROM players WHERE name = ?Name;";
cmd.Parameters.AddWithValue("Name", myName);
MySqlDataReader Reader = cmd.ExecuteReader();
if (!Reader.HasRows) return;
while (Reader.Read())
{
Console.WriteLine(GetDBString("column1", Reader);
Console.WriteLine(GetDBString("column2", Reader);
}
Reader.Close();
conn.Close();
}
}
private string GetDBString(string SqlFieldName, MySqlDataReader Reader)
{
return Reader[SqlFieldName].Equals(DBNull.Value) ? String.Empty : Reader.GetString(SqlFieldName);
}
Note that I am using a method to return a specific value if the database value is null. You can get creative and provide various return values or incorporate nullable types, etc.
Also you can use:
Create your own dataTable. When reader reaches end, you will have datatable which is custom created, and custom filled by yourself.
DataTable dt = new DataTable();
dt.Columns.Add("Id",typeof(int));
dt.Columns.Add("Name",typeof(string));
dt.Columns.Add("BlaBla",typeof(string));
dt.AcceptChanges();
// Your DB Connection codes.
while(dr.Read())
{
object[] row = new object[]()
{
dr[0].ToString(),// ROW 1 COLUMN 0
dr[1].ToString(),// ROW 1 COLUMN 1
dr[2].ToString(),// ROW 1 COLUMN 2
}
dt.Rows.Add(row);
}