using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.Odbc;
using System.Data.SqlClient;
namespace BroNetNew.Models
{
public class DataConn
{
string MyConString = "Driver={MySQL ODBC 5.3 Unicode Driver};" +
"SERVER=localhost;" +
"DATABASE=Bee;" +
"UID=root;" +
"PASSWORD=123;" +
"OPTION=4";
OdbcConnection MyConnection = new OdbcConnection(myConString);
MyConnection.Open();
string sql = "SELECT * from member";
OdbcConnection conn = null;
OdbcCommand comm = null;
OdbcDataReader dr = null;
conn = new OdbcConnection(MyConString);
conn.Open();
comm = new OdbcCommand(sql, conn);
dr = comm.ExecuteReader();
}
}
I don't know how to make it work and how to get data from table member(MY DB name:Bee in MyConString)
Please Help ... I First time use asp.net MVC.
Thank You...
public class DataConn
{
string MyConString = "Driver={MySQL ODBC 5.3 Unicode Driver};" +
"SERVER=localhost;" +
"DATABASE=Bee;" +
"UID=root;" +
"PASSWORD=123;" +
"OPTION=4"; // ODBC connection
string Query = "SELECT * from member"; // Write Query
using (OdbcConnection c = new OdbcConnection(myConString)) //New Connection
{
OdbcCommand cmd = new OdbcCommand(Query, c);
c.Open(); // Connection Open
OdbcDataReader dr = cmd.ExecuteReader();
// dr will get all data u want
// Query better use "SELECT column[0], column[1] FROM `member`";
// dr.GetString(0); -> for column[0]
// dr.GetString(1); -> for column[1]
// do something...
}
}
Related
I'm trying to store some Arabic values I got from a web service, but when I select them from the database and show them in a DataGridView it just shows "?????". The three columns in the database are nvarchar(50). How should I be storing them?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Data.SqlClient;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
string user = "gamal";
string p1 = "GAM123";
string p2 = "GAM123";
string sdate = "05152014000000";
string edate = "05182014235959";
string node = "232641";
string group = "Al Ahsa - ???????";
string Compress = "";
string m_d = "sa";
string lang = "1";
DataSet ds = new DataSet();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
test_ws.ppppWebServiceSoapClient ws =
new test_ws.ppppWebServiceSoapClient("pppp Report Web ServiceSoap");
ds = ws.GetGroups(user, p1, p2);
DataSet ds_ra = new DataSet();
ds_ra = ws.RegionAlarm(user, p1, p2, sdate, edate, node, group, Compress, m_d, lang);
ds_ra.WriteXml("region_alarm.xml");
string connetionString = null;
SqlConnection connection;
SqlCommand command ;
SqlDataAdapter adpter = new SqlDataAdapter();
string sql = null;
string ID = null;
string nodegroup = null;
string nodecount = null;
connetionString = #"Server=.\SQLEXPRESS; DataBase=hhhh; Integrated Security=True;";
connection = new SqlConnection(connetionString);
int i = 0;
connection.Open();
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
ID = ds.Tables[0].Rows[i].ItemArray[0].ToString();
nodegroup = ds.Tables[0].Rows[i].ItemArray[1].ToString();
nodecount = ds.Tables[0].Rows[i].ItemArray[2].ToString();
sql = "insert into groups (id,nodegroup,nodecount)
values(" + ID + ",'" + nodegroup + "'," + nodecount + ")";
command = new SqlCommand(sql, connection);
adpter.InsertCommand = command;
adpter.InsertCommand.ExecuteNonQuery();
}
sql = "select * from groups";
command = new SqlCommand(sql, connection);
adpter.SelectCommand = command;
adpter.SelectCommand.ExecuteNonQuery();
DataTable dt = new DataTable();
adpter.Fill(dt);
dataGridView1.DataSource = dt;
connection.Close();
MessageBox.Show("Done ..تم ");
}
}
}
After ensuring the NodeGroup column in your table is an NVARCHAR(), use parameters instead of concatenation, for both preventing SQL injection, and to make sure your data types are properly set. When you were concatenating the sql, the string literal was a varchar, unless you put an N in front of the literal.
sql = "insert into groups (id,nodegroup,nodecount)
values(#ID,#NodeGroup, #NodeCount)";
command = new SqlCommand(sql, connection);
command.Parameters.AddWithValue("#ID", id);
command.Parameters.AddWithValue("#NodeGroup", nodegroup);
command.Parameters.AddWithValue("#NodeCroup", nodecount);
adpter.InsertCommand = command;
adpter.InsertCommand.ExecuteNonQuery();
Change this:
values(" + ID + ",'" + nodegroup + "'," + nodecount + ")";
into
values(" + ID + ", N'" + nodegroup + "'," + nodecount + ")";
However, you should really be using parameters instead of building an SQL string with the values in it. That will get you around all of the escaping issues.
When inserting in to database with inline sql you have to prefix the nvarchar value with 'N'. For example: insert into mytable (col1) values (N'myvalue')
I am trying to create a simple website in VS Express for Web 2013 which can interact with a database "Parts." My database is stored in the app_data folder. I am able to view the connection in the Server Explorer, which implies the connection string is saved. However, the following code throws 2 errors:
Error 13 The best overloaded method match for 'System.Data.SqlClient.SqlCommand.SqlCommand(string, System.Data.SqlClient.SqlConnection)' has some invalid arguments
Error 14 Argument 2: cannot convert from 'string' to 'System.Data.SqlClient.SqlConnection'
I don't know how to remedy this. Here is my c# code:
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void insertButton_Click(object sender, EventArgs e)
{
string connstring = System.Configuration.ConfigurationManager.ConnectionStrings["connect"].ConnectionString;
SqlCommand cmd = new SqlCommand("INSERT INTO PARTS VALUES('" + nameBox.Text + "', '" + descriptionBox.Text + "', '" + quantityBox.Text + "', '" + categoryList.SelectedValue + "')", connstring);
cmd.ExecuteNonQuery();
}
}
I'm completely new to c#, so please keep that in mind. Thanks for your help.
UPDATE: The following code throws two errors, both of which are:
Error 15 The name 'conn' does not exist in the current context
I'm new to c#, but it doesn't look like there's anything wrong with the code. The name "conn" is clearly defined right above.
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void insertButton_Click(object sender, EventArgs e)
{
using (var conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["connect"].ConnectionString))
using (var cmd = new SqlCommand(
"INSERT INTO PARTS VALUES(#name, #description, #quantity, #category)", conn))
{
cmd.Parameters.AddWithValue("name", nameBox.Text);
cmd.Parameters.AddWithValue("description", descriptionBox.Text);
cmd.Parameters.AddWithValue("quantity", quantityBox.Text);
cmd.Parameters.AddWithValue("category", categoryList.SelectedValue);
conn.Open();
cmd.ExecuteNonQuery();
}
}
}
using(var conn = new SqlConnection(connectionString))
{
conn.Open();
// use conn to create the command
}
But important: YOUR SQL IS REALLY REALLY DANGEROUS. That is open to SQL injection, a HUGE and trivially easy attack surface. Please please parameterize that.
For example:
using(var conn = new SqlConnection(connectionString))
using(var cmd = new SqlCommand(
"INSERT INTO PARTS VALUES(#name, #description, ...)", conn))
{
cmd.Parameters.AddWithValue("name", nameBox.Text);
cmd.Parameters.AddWithValue("description", descriptionBox.Text);
//...
conn.Open();
cmd.ExecuteNonQuery();
}
(note you need to add a few yourself; I have left it incomplete, just name and description used for example)
What is connect value from your config?
Can you try
SqlConnection conn = new SqlConnection(connstring);
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
and now issue the query.
You need to create a SqlConnection first:
string connstring = System.Configuration.ConfigurationManager.ConnectionStrings["connect"].ConnectionString;
SqlConnection conn = new SqlConnection(connstring);
SqlCommand cmd = new SqlCommand("INSERT INTO PARTS VALUES('" + nameBox.Text + "', '" + descriptionBox.Text + "', '" + quantityBox.Text + "', '" + categoryList.SelectedValue + "')"
, conn);
cmd.ExecuteNonQuery();
Some early habits to get into:
Do not concatenate SQL strings. This is for several reasons, not the least of which is the vulnerability to SQL Injection attacks.
wrap your connection and command in using statements. That ensures that the connections are closed properly if there is an exception.
The end result will look something like:
string connstring = ConfigurationManager.ConnectionStrings["connect"].ConnectionString;
using(SqlConnection conn = new SqlConnection(connstring))
{
string sql = "INSERT INTO PARTS VALUES(#name, #description, #quantity, #categoryList)"
using(SqlCommand cmd = new SqlCommand(sql , conn))
{
cmd.Parameters.AddWithValue("#name", nameBox.Text);
... etc.
cmd.ExecuteNonQuery();
}
}
My requirement is to read Date column from access file and use one value to append it to a file name, so as to create file with date timestamp using the db value.
I am trying following approach but it gives me exception "No data exists for the row/column":
here's the code
OleDbConnection conn = new OleDbConnection(connectionString);
OleDbConnection conn1 = new OleDbConnection(connectionString);
string dt = "SELECT top 1 Date FROM Events";
OleDbCommand cmd1 = new OleDbCommand(dt, conn1);
conn1.Open();
OleDbDataReader rdr = cmd1.ExecuteReader();
string time_stmp = rdr.GetInt32(0).ToString();
rdr.Close();
conn1.Close();
string path = text_dir + "\\" + time_stmp + "_" + "BWC_Ejournal.txt";
You'll need to call the Read() method on the OleDbDataReader object before accessing its data.
E.g.
OleDbDataReader rdr = cmd1.ExecuteReader();
string time_stmp = "";
if(rdr.Read())
{
time_stmp = rdr.GetInt32(0).ToString();
}
else
{
//handle no data situation here
}
This will also allow to handle a situation where no data is returned more gracefully too.
DATE is a reserved word in ACE/Jet SQL. Try this instead:
string dt = "SELECT TOP 1 [Date] FROM Events";
Edit
On taking a closer look at your code I notice that you create the OleDbCommand object before the connection is opened. I've seen that cause problems as well. FWIW, the following code works for me:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.OleDb;
namespace oleDbTest
{
class Program
{
static void Main(string[] args)
{
using (var con = new OleDbConnection(
"Provider=Microsoft.ACE.OLEDB.12.0;" +
#"Data Source=C:\__tmp\main.accdb;"))
{
con.Open();
using (var cmd = new OleDbCommand(
"SELECT TOP 1 [Date] FROM [Events]", con))
{
string time_stmp = Convert.ToDateTime(cmd.ExecuteScalar()).ToString("yyyyMMdd");
Console.WriteLine(time_stmp.ToString());
}
con.Close();
}
Console.WriteLine("Done.");
System.Threading.Thread.Sleep(2000);
}
}
}
I'm working on a .Net Desktop app that uses Access database. I'm using the Contacts form and trying to change the Category field, which has multiple choices in a combo box for value. The value I'm trying to set is in the list of choices, but it doesn't do anything. Here is my code. Please shed some light on what's going on. That code seems to be working for a DELETE command.
string list = string.Join(", ", f);
string ConnStr = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + txtDB.Text + "";
string ComStr = "UPDATE Contacts SET Category = ? where [E-mail Address] in (?)";
using (OleDbConnection con = new OleDbConnection(ConnStr))
{
con.Open();
using (OleDbCommand com = new OleDbCommand(ComStr, con))
{
com.Parameters.AddWithValue("List", list);
com.Parameters.AddWithValue("Category", "Не получава мейли");
com.ExecuteNonQuery();
}
con.Close();
}
I think this should work:-
string ComStr = "UPDATE Contacts SET Category = #Category where [E-mail Address] in #List";
using (OleDbConnection con = new OleDbConnection(ConnStr))
{
con.Open();
using (OleDbCommand com = new OleDbCommand(ComStr, con))
{
com.Parameters.AddWithValue("#Category", "Не получава мейли");
com.Parameters.AddWithValue("#List", list);
com.ExecuteNonQuery();
}
con.Close();
}
I found the answer. Every item in the list must be in... ok i don't know the word, but here's my working code:
string list = string.Join("', '", f);
string l = "'" + list + "'";
string ConnStr = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + txtDB.Text + "";
string ComStr = "UPDATE Contacts SET Category = #Category where [E-mail Address] in (" + l + ")";
using (OleDbConnection con = new OleDbConnection(ConnStr))
{
con.Open();
using (OleDbCommand com = new OleDbCommand(ComStr, con))
{
com.Parameters.AddWithValue("Category", "Не получава мейли");
com.ExecuteNonQuery();
}
con.Close();
}
Thanks for the tips and the time guys.
What's the simplest way to connect and query a database for a set of records in C#?
#Goyuix -- that's excellent for something written from memory.
tested it here -- found the connection wasn't opened. Otherwise very nice.
using System.Data.OleDb;
...
using (OleDbConnection conn = new OleDbConnection())
{
conn.ConnectionString = "Provider=sqloledb;Data Source=yourServername\\yourInstance;Initial Catalog=databaseName;Integrated Security=SSPI;";
using (OleDbCommand cmd = new OleDbCommand())
{
conn.Open();
cmd.Connection = conn;
cmd.CommandText = "Select * from yourTable";
using (OleDbDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
Console.WriteLine(dr["columnName"]);
}
}
}
}
Very roughly and from memory since I don't have code on this laptop:
using (OleDBConnection conn = new OleDbConnection())
{
conn.ConnectionString = "Whatever connection string";
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.Connection = conn;
cmd.CommandText = "Select * from CoolTable";
using (OleDbDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
// do something like Console.WriteLine(dr["column name"] as String);
}
}
}
}
That's definitely a good way to do it. But you if you happen to be using a database that supports LINQ to SQL, it can be a lot more fun. It can look something like this:
MyDB db = new MyDB("Data Source=...");
var q = from db.MyTable
select c;
foreach (var c in q)
Console.WriteLine(c.MyField.ToString());
This is an alternative way (DataReader is faster than this one):
string s = "";
SqlConnection conn = new SqlConnection("Server=192.168.1.1;Database=master;Connect Timeout=30;User ID=foobar;Password=raboof;");
SqlDataAdapter da = new SqlDataAdapter("SELECT TOP 5 name, dbid FROM sysdatabases", conn);
DataTable dt = new DataTable();
da.Fill(dt);
for (int i = 0; i < dt.Rows.Count; i++)
{
s += dt.Rows[i]["name"].ToString() + " -- " + dt.Rows[i]["dbid"].ToString() + "\n";
}
MessageBox.Show(s);
If you are intending on reading a large number of columns or records it's also worth caching the ordinals and accessing the strongly-typed methods, e.g.
using (DbDataReader dr = cmd.ExecuteReader()) {
if (dr.Read()) {
int idxColumnName = dr.GetOrdinal("columnName");
int idxSomethingElse = dr.GetOrdinal("somethingElse");
do {
Console.WriteLine(dr.GetString(idxColumnName));
Console.WriteLine(dr.GetInt32(idxSomethingElse));
} while (dr.Read());
}
}
If you are querying a SQL Server database (Version 7 and up) you should replace the OleDb classes with corresponding classes in the System.Data.SqlClient namespace (SqlConnection, SqlCommand and SqlDataReader) as those classes have been optimized to work with SQL Server.
Another thing to note is that you should 'never' select all as this might lead to unexpected results later on if you add or remove columns to this table.
I guess, you can try entity framework.
using (SchoolDBEntities ctx = new SchoolDBEntities())
{
IList<Course> courseList = ctx.GetCoursesByStudentId(1).ToList<Course>();
//do something with courselist here
}
Charge the libraries
using MySql.Data.MySqlClient;
This is the connection:
public static MySqlConnection obtenerconexion()
{
string server = "Server";
string database = "Name_Database";
string Uid = "User";
string pwd = "Password";
MySqlConnection conect = new MySqlConnection("server = " + server + ";" + "database =" + database + ";" + "Uid =" + Uid + ";" + "pwd=" + pwd + ";");
try
{
conect.Open();
return conect;
}
catch (Exception)
{
MessageBox.Show("Error. Ask the administrator", "An error has occurred while trying to connect to the system", MessageBoxButtons.OK, MessageBoxIcon.Error);
return conect;
}
}