I am getting an error when I try to run my program which says -
An unhandled exception of type 'System.ArgumentException' occurred in System.Data.dll
Additional information: Initialiseringsstrengens format does not match the specification starting at index 0.
at using (conn = new SqlConnection(connstring))
the whole code for that -
public partial class MainWindow : Window
{
public SqlConnection conn;
public SqlCommand cmd;
string connstring = (#"Data Source=SINDALSQL\MSSQL14; Initial Catalog=OminiData; Integrated Security =True");
string sql = ("SELECT Mærke, Model, Årgang, [Motor Type], Krydsmål, Centerhul, Møtrik, Bolter, Dæk, Fælge FROM Hjuldata");
private void binddata()
{
DataSet1 ds = new DataSet1();
using (conn = new SqlConnection(connstring))
{
cmd = new SqlCommand(sql, conn);
SqlDataAdapter adp = new SqlDataAdapter();
conn.Open();
adp.SelectCommand = cmd;
adp.Fill(ds, "Hjuldata");
hjuldata.DataContext = ds;
}
}`
public partial class MainWindow : Window {
public SqlConnection conn;
public SqlCommand cmd;
string connstring = (#"Data Source=SINDALSQL\MSSQL14; Initial Catalog=OminiData; Integrated Security =True");
string sql= ("SELECT Mærke, Model, Årgang, [Motor Type], Krydsmål, Centerhul, Møtrik, Bolter, Dæk, Fælge FROM Hjuldata");
private void binddata() {
DataTable dt = new DataTable();
using (SqlDataAdapter adp = new SqlDataAdapter(sql,connstring)) {
adp.Fill(dt);
hjuldata.DataContext = dt;
}
}
}
Related
I've successfully built up my method to execute a select command. It is working fine. Then I change my code for SqlDataAdapter DA = new SqlDataAdapter();
I tried to pass SqlCommand as CommandType.Text in the parameters but I can not do it successfully. I get error. Is there any way if I can pass it as parameters. Please see my code.
Running code (aspx page code)
if ((!string.IsNullOrEmpty(user_login.Value)) && (!string.IsNullOrEmpty(user_pass.Value)))
{
// username & password logic
DataTable dt = new DataTable();
string strQuery = "SELECT 1 FROM TBL_USER_INFO WHERE USERNAME = #USERNAME AND PASSWORD = #PASSWORD";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("#USERNAME", SqlDbType.VarChar).Value = user_login.Value.Trim();
cmd.Parameters.Add("#PASSWORD", SqlDbType.VarChar).Value = user_pass.Value.Trim();
DBConnection conn_ = new DBConnection();
dt = conn_.SelectData(cmd);
if (conn_.SQL_dt.Rows.Count > 0)
{
Response.Redirect("Home.aspx", false);
}
}
Successful connection class code
public DataTable SelectData(SqlCommand command)
{
try
{
conn.Open();
SqlDataAdapter DA = new SqlDataAdapter();
command.CommandType = CommandType.Text;
command.Connection = conn;
DA.SelectCommand = command;
DA.Fill(SQL_dt);
return SQL_dt;
}
catch (Exception ex)
{
return null;
}
finally
{
conn.Close();
}
}
How can I pass CommandType.Text as parameters for SqlDataAdapter?
Error code
public DataTable SelectData(SqlCommand command)
{
try
{
conn.Open();
SqlDataAdapter DA = new SqlDataAdapter(command.CommandType.ToString(), conn);
// command.CommandType = CommandType.Text;
// command.Connection = conn;
DA.SelectCommand = command;
DA.Fill(SQL_dt);
return SQL_dt;
}
catch (Exception ex)
{
return null;
}
finally
{
conn.Close();
}
}
I am getting this error:
System.InvalidOperationException: Fill: SelectCommand.Connection property has not been initialized.
at System.Data.Common.DbDataAdapter.GetConnection3(DbDataAdapter adapter, IDbCommand command, String method)...
public DataTable SelectData(string query)
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection("Your Connection String here"))
{
con.Open();
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter adp = new SqlDataAdapter(cmd))
{
adp.Fill(dt);
return dt;
}
}
}
}
To use:
SelectData("select * from yourTable");
Reds has the answer. Just to clean the code up a little bit...
public DataTable SelectData(string query)
{
using (var connection = new SqlConnection("myConnectionString"))
using (var command = new SqlCommand(query, connection))
using (var adapter = new SqlDataAdapter(command))
{
var dt = new DataTable();
connection.Open();
adapter.Fill(dt);
return dt;
}
}
Actually you should pass the connection object on SQLCommand.Hope it helped you
DBConnection conn_ = new DBConnection();
SqlCommand cmd = new SqlCommand(strQuery,conn_);
The error that you are getting is not related to CommandType.Text, it says you have initialised the connection property of of SelectCommand. Basically you should uncomment "command.Connection = conn;" to get rid of this error. If you still face any other issue , it is better to provide those details in the questions to provide accurate answer.
I got two classes, one for db connection and another to get data. When I use the SqlCommand type as stored procedure it returns the data table properly, but when I change the command type to text and change the command text properly it returns a null value. Why is this happening?
Class 1
public class DB_Connection
{
public SqlConnection cnn;
public SqlCommand cmd;
public SqlDataAdapter ada;
public DB_Connection()
{
cnn = new SqlConnection("Data Source=svr01;Initial Catalog=PDFScramble;Integrated Security=True");
cnn.Open();
cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;// *changed in here SP or Text*
cmd.Connection = cnn;
ada = new SqlDataAdapter();
ada.SelectCommand = cmd;
}
Class 2
public class Data : DB_Connection
{
public string DException { get; set; }
public DataTable Datatable { get; set; }
public bool GetCivicEntities()
{
try
{
cmd.CommandText = "SELECT Id, Description, StateId ,EntityTypeId FROM CivicEntities";
ada.Fill(Datatable);// *Null in here*
return true;
}
catch (Exception ex)
{
DException = ex.Message;
return false;
}
}
Your Datatable is null, because of that you have this problem. This should fix it.
cmd.CommandText = "SELECT Id, Description, StateId ,EntityTypeId FROM CivicEntities";
Datatable = new DataTable();
ada.Fill(Datatable);
return true;
There is something wrong with the class structure. Check with this
using (SqlConnection conn = new SqlConnection("connectionString"))
{
SqlCommand cmd = null;
SqlParameter prm = null;
SqlDataAdapter dad = null;
DataTable dt = new DataTable();
cmd = new SqlCommand("SPName", conn);
cmd.CommandType = CommandType.StoredProcedure;
conn.Open();
dad = new SqlDataAdapter(cmd);
dad.Fill(dt);
conn.Close();
}
using (SqlConnection conn = new SqlConnection("connectionString"))
{
SqlCommand cmd = null;
SqlParameter prm = null;
SqlDataAdapter dad = null;
DataTable dt = new DataTable();
cmd = new SqlCommand("select * from dummy",conn);
cmd.CommandType = CommandType.StoredProcedure;
conn.Open();
dad = new SqlDataAdapter(cmd);
dad.Fill(dt);
conn.Close();
}
In a simple datagridview it gives me error when run (Compilation Error):(Source Error:
Line 11:
Line 12:
Line 13: )
mycode
public partial class website : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Fillgrid();
}
public void Fillgrid()
{
Dataset ds = new Dataset();
SqlConnection cn = new SqlConnection(#"Server=.\SQLEXPRESS; DataBase=first; Integrated Security=true;");
cn.Open();
SqlCommand cmd;
cmd = new SqlCommand("select * from attendance", cn);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(ds);
cn.Close();
selectGridView.DataSource = ds;
selectGridView.DataBind();
}
}
I think you can use the following code!!
Dataset ds = new Dataset();
SqlConnection cn = new SqlConnection(#"Server=.\SQLEXPRESS; DataBase=first; Integrated Security=true;");
cn.Open();
SqlDataAdapter adapter = new SqlDataAdapter("select * from attendance", cn);
adapter.Fill(ds,"attendance");
cn.Close();
selectGridView.DataSource = ds;
selectGridView.DataBind();
I found this code online, which connects from C# to an SQL server database.
I wish to do something similar, but I want to connect to an Access 2010 database.
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
namespace WindowsFormsApplication1.DAL
{
public class PersonDAL
{
public string ConString =
"Data Source=SOURAV-PC\\SQL_INSTANCE;Initial Catalog=test;Integrated Security=True";
SqlConnection con = new SqlConnection();
DataTable dt = new DataTable();
public DataTable Read()
{
con.ConnectionString = ConString;
if (ConnectionState.Closed == con.State)
con.Open();
SqlCommand cmd = new SqlCommand("select * from Person",con);
try
{
SqlDataReader rd = cmd.ExecuteReader();
dt.Load(rd);
return dt;
}
catch
{
throw;
}
}
public DataTable Read(Int16 Id)
{
con.ConnectionString = ConString;
if (ConnectionState.Closed == con.State)
con.Open();
SqlCommand cmd = new SqlCommand("select * from Person where ID= "+ Id +"", con);
try
{
SqlDataReader rd = cmd.ExecuteReader();
dt.Load(rd);
return dt;
}
catch
{
throw;
}
}
}
}
How should I change my code to do that ?
For the example, let's assume that my access DB is in: C:\VisualStudioProject\Sample
Thank you!
You need to do the following:
Use Connection string as:
string connectionstring = Standard security
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\myFolder\myAccessFile.accdb;
Persist Security Info=False;
Use OLEDB instead of SQL
OleDbConnection MyConn = new OleDbConnection(connectionstring);
public class PersonDAL
{
public string ConString =
#"Standard security Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\myFolder\myAccessFile.accdb; Persist Security Info=False;";
OleDbConnection con;
DataTable dt;
public PersonDAL()
{
con = new OleDbConnection();
dt = new DataTable();
}
public DataTable Read()
{
con.ConnectionString = ConString;
if (ConnectionState.Closed == con.State)
con.Open();
OleDbCommand cmd = new OleDbCommand("select * from Person", con);
try
{
OleDbDataReader rd = cmd.ExecuteReader();
dt.Load(rd);
return dt;
}
catch
{
throw;
}
}
public DataTable Read(Int16 Id)
{
con.ConnectionString = ConString;
if (ConnectionState.Closed == con.State)
con.Open();
OleDbCommand cmd = new OleDbCommand("select * from Person where ID= " + Id + "", con);
try
{
OleDbDataReader rd = cmd.ExecuteReader();
dt.Load(rd);
return dt;
}
catch
{
throw;
}
}
}
I have an object below:
public class DatabaseAccess
{
private static string sConnStr;
private static SqlConnection sqlConn;
private static string ConnectionString
{
get
{
if (String.IsNullOrEmpty(sConnStr))
{
sConnStr = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
}
return sConnStr;
}
}
public static int OpenConnection
{
get
{
sqlConn = new SqlConnection(ConnectionString);
return 0;
}
}
public static SqlConnection Connection
{
get
{
if (sqlConn.State != ConnectionState.Open)
{
sqlConn = new SqlConnection(ConnectionString);
sqlConn.Open();
}
return sqlConn;
}
}
}
So whenever I need a connection in my web application, I use something like:
DataTable dt = new DataTable();
using (SqlConnection cnn = DatabaseAccess.Connection)
{
using (SqlDataAdapter da = new SqlDataAdapter("MyAStoredProcedure", cnn))
{
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.Fill(dt);
}
}
return dt;
It all seems well except when there are 2 users running the codes at the same time, I will get in my web application the following error:
There is already an open DataReader associated with this Command needs to be Closed.
I need some advice how do I resolve the above issue?
Thank you.
That's because you're sharing connection objects - don't do that. DatabaseAccess.Connection should create a new SqlConnection every time.
Try to create a new instance of SqlConnection in the using statement
DataTable dt = new DataTable();
using (SqlConnection cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
{
cnn.Open();
using (SqlDataAdapter da = new SqlDataAdapter("MyAStoredProcedure", cnn))
{
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.Fill(dt);
}
}
return dt;