I am trying to upload a Microsoft Access Database into a Microsoft SQL Server Express Database.
The structure of the Access and the SQL Database are identical except for the name of the Primary Key.
Error Code:
System.InvalidOperationException: No data exists for the row/column. at System.Data.OleDb.OleDbDataReader.DoValueCheck(Int32 ordinal) at System.Data.OleDb.OleDbDataReader.GetValue(Int32 ordinal) at System.Data.OleDb.OleDbDataReader.get_Item(Int32 index) at ACCESStoMDF._Default.Button1_Click(Object sender, EventArgs e) in C:\Users\path2ACCESStoMDF\ACCESStoMDF\Default.aspx.cs:line 44
web.config
<configuration>
<connectionStrings>
<add name="ACCESSdb"
connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\path1\DBaccess.accdb;Persist Security Info=False;" />
<add name="MSSQLdb"
connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\MSSQLdb.mdf;User Instance=true;"
providerName="System.Data.SqlClient" />
</connectionStrings>
MSAccessTOMSSQL.aspx.cs
protected void Button1_Click(object sender, EventArgs e)
{
String connStr = ConfigurationManager.ConnectionStrings["ACCESSdb"].ConnectionString;
String cmdStr = "SELECT * FROM [TableACCESS];";
try
{
using (OleDbConnection conn = new OleDbConnection(connStr))
{
using (OleDbCommand cmd = new OleDbCommand(cmdStr, conn))
{
conn.Open();
using (OleDbDataReader dr = cmd.ExecuteReader())
{
String connStr1 = ConfigurationManager.ConnectionStrings["MSSQLdb"].ConnectionString;
String cmdStr1 = "INSERT INTO [Table1] (col1,col2,col3) VALUES (#col1,#col2,#col3);";
try
{
using (SqlConnection conn1 = new SqlConnection(connStr1))
{
using (SqlCommand cmd1 = new SqlCommand(cmdStr1, conn1))
{
conn1.Open();
cmd1.Parameters.AddWithValue("#col1", dr[1]);
cmd1.Parameters.AddWithValue("#col2", dr[2]);
cmd1.Parameters.AddWithValue("#col3", dr[3]);
cmd1.ExecuteNonQuery();
conn1.Close();
cmd1.Dispose();
conn1.Dispose();
}
}
}
catch (Exception ex)
{
Label2.Text = "Insert Into: " + ex.ToString();
}
}
conn.Close();
cmd.Dispose();
conn.Dispose();
}
}
}
catch (Exception ex)
{
Label2.Text = "Access: " + ex.ToString();
}
}
An OleDbDataReader allows you to process the results of a SELECT query row-by-row. As shown in the documentation, you need to do something like
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader[0].ToString());
}
reader.Close();
Note also that the numeric index of the returned row is zero-based, so the first column is reader[0].
Related
I'm unable to insert data into table. we are using local db. I'm not even getting any exception
string constr = ConfigurationManager.ConnectionStrings["server"].ConnectionString;
private void button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand("insert into Client_Name(Name) values('" + textBox1.Text + "')",con);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception ee)
{
Console.Write("Exception");
}
}
In app.config
<connectionStrings>
<add name="server" connectionString="Data Source = (LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\msm.mdf;Integrated
Security=True;Connect Timeout=30" providerName="System.Data.SqlClient" />
</connectionStrings>
I have tried all the possible way, and got the best solution considering your scenario.
During an hour observation got to know due database connection
persistence issue you were having that problem try below snippet would
work as expected.
string connectionString = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\msm.mdf;Connect Timeout=30;Integrated Security=True;";
using (var _connection = new SqlConnection(connectionString))
{
_connection.Open();
using (SqlCommand command = new SqlCommand("Insert into [LocalTestTable] values (#name,#description)", _connection))
{
command.Parameters.AddWithValue("#name", "TestFlatName");
command.Parameters.AddWithValue("#description", "TestFlatDescription");
SqlDataReader sqlDataReader = command.ExecuteReader();
sqlDataReader.Close();
}
_connection.Close();
}
Hope that will resolve your problem without having anymore issue.
I've always used Oledb Connection.
but now I need to connect with my Database via Sql connection
yet I don't know how to do so,
can some one provide me an example of a database connected with sql connection?
this code needs a sql connection to be done successfully.
protected void Button1_Click(object sender, EventArgs e)
{
string st = this.TextBox1.Text;
string sqlstr2 = "select * from hsinfo WHERE rname='"+st+ "'";
SqlCommand cmd = new SqlCommand(sqlstr2,);
using (SqlDataReader rd = cmd.ExecuteReader())
{
this.Label1.Text = rd["rmail"].ToString();
}
}
You can check the official Microsoft page for more details SqlConnection Class, but I will reproduce the given example below ...
Aditionally you can check also the Connection String Syntax linked in the previous link.
private static void CreateCommand(string queryString,
string connectionString)
{
using (SqlConnection connection = new SqlConnection(
connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
command.Connection.Open();
command.ExecuteNonQuery();
}
}
This is a simple example code and it's working. This might help you.
Here NextMonth,NextYear,ProcessedDate are auto calculated values comes from another function don't think about that.
String cs = #"Data Source=LENOVO-G510;Initial Catalog=Nelna2;Persist Security Info=True;User ID=sa;Password=123";
protected void Save_Click(object sender, EventArgs e)
{
// SqlConnection con = new SqlConnection(cs);
using (SqlConnection con = new SqlConnection(cs))
{
try
{
SqlCommand command5 = new SqlCommand("insert into MonthEnd (month,year,ProcessedDate) values (#month2,#year2,#ProcessedDate2) ", con);
command5.Parameters.AddWithValue("#month2", NextMonth);
command5.Parameters.AddWithValue("#year2", NextYear);
command5.Parameters.AddWithValue("#ProcessedDate2", ProcessedDate);
command5.ExecuteNonQuery();
}
catch (SqlException ex)
{
Response.Write(ex.Message);
}
}
}
Connection string can be found in DB properties. right click on DB -> properties and Get the Connection String
There is no enougth information to build connection for you, but in the shortes you sth like this:
Server=...;Database=...;User ID=...;Password=...;
For more information just check ConnectionStrings website.
try below code and for more information about c# SQL server connection see this SQL Server Connection
string connetionString = null;
SqlConnection cnn ;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password"
cnn = new SqlConnection(connetionString);
try
{
cnn.Open();
MessageBox.Show ("Connection Open ! ");
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
I would do something like this:
public static List<Test> GetTests(string testVariable)
{
DataTable result = new DataTable();
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Database"].ConnectionString))
{
connection.Open();
GetQuery(
connection,
QueryGetTests,
ref result,
new List<SqlParameter>()
{
new SqlParameter("#testVariable", testVariable)
}
);
return result.Rows.OfType<DataRow>().Select(DataRowToTest).ToList();
}
}
private static void GetQuery(SqlConnection connection, string query, ref DataTable dataTable, List<SqlParameter> parameters = null)
{
dataTable = new DataTable();
using (SqlCommand command = new SqlCommand(query, connection))
{
command.CommandTimeout = 120;
if (parameters != null)
{
foreach (SqlParameter parameter in parameters)
{
command.Parameters.Add(parameter);
}
}
using (SqlDataAdapter reader = new SqlDataAdapter(command))
{
reader.Fill(dataTable);
}
}
}
I think this can help you.
string sqlString = "select * from hsinfo WHERE rname=#st";
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseName"].ConnectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(sqlString, conn))
{
cmd.Parameters.Add("#st", st);
using (SqlDataReader rd = cmd.ExecuteReader())
{
if (rd.Read())
{
this.Label1.Text = rd["rmail"].ToString();
}
}
}
}
Trick:
Create a file with .udl Extension on your Desktop
Run it by Double click
Compile form by Choosing provider, username, password, etc...
Test connection and save
Close the form
Open now the .udl file with Notepad
You will see the connection string that you can use with ADO.NET
I try to insert data into my database, all operations are done successfully but database does not update after the SQL query was executed. It is windows based application. I put the connection string in app.config file.
When I run this application code. and insert the data it show me the msg "Data inserted", but when I check the database there no data updated in database.... give me some solution.
I use Visual Studio 2013 and SQL Server 2012.
Here is my code:
namespace Sample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["cons"].ConnectionString.ToString());
sqlcon.Open();
string str = "insert into tab(name,pwd) values('" + textBox1.Text.ToString() + "','" + textBox2.Text.ToString() + "')";
SqlCommand cmd = new SqlCommand(str, sqlcon);
cmd.ExecuteNonQuery();
MessageBox.Show("Data inserted");
cmd.Clone();
}
catch(Exception E)
{
MessageBox.Show("No data inserted");
}
}
}
}
App.config
<configuration>
<connectionStrings>
<add name="cons"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename='|DataDirectory|\Database1.mdf';Integrated Security=True"/>
</connectionStrings>
</configuration>
hey i solve this problem myself
i just replace the full path in connection string with (|DataDirectory|\Database.mdf).... like this
<configuration>
<connectionStrings>
<add name="cons" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename='C:\Users\Dhaval\documents\visual studio 2013\Projects\Sample\Sample\Database.mdf';Integrated Security=True"/>
</connectionStrings>
</configuration>
so the connection string access right database of application.. not(.\bin\debug) "Database.mdf" file..
Firstly, to prevent injection attacks and to avoid syntax errors, use parameters. Secondly, to ensure resources are properly disposed of, use the "using" statements. Thirdly, show the error message thrown. The following (untested) code illustrates these techniques. Also, what is the cmd.Clone() used for?
private void button1_Click(object sender, EventArgs e)
{
SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["cons"].ConnectionString.ToString());
try
{
using (sqlcon)
{
sqlcon.Open();
string str = "insert into tab(name,pwd) values(#Value1, #Value2)";
using (SqlCommand cmd = new SqlCommand(str, sqlcon))
{
cmd.Parameters.Add(new SqlParameter("Value1", TextBox1.Text));
cmd.Parameters.Add(new SqlParameter("Value2", TextBox2.Text));
cmd.ExecuteNonQuery();
MessageBox.Show("Data inserted");
//cmd.Clone();
}
}
}
catch (Exception E)
{
throw new Exception(E.Message);
}
finally
{
sqlcon.Close();
}
}
Here is the code
public string connectionString = ConfigurationManager.AppSettings["myconnection"];
public int get_details(string team1_name, string team2_name)
{
SqlConnection con = new SqlConnection(connectionString);
string sql = "insert into Table(team1_name,team2_name) values(#team1_name,#team2_name)";
SqlCommand cmd = new SqlCommand(sql,con);
cmd.Parameters.AddWithValue("#team1_name", team1_name);
cmd.Parameters.AddWithValue("#team2_name", team2_name);
try
{
con.Open();
return cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
}
}
Whenever I run this code, the error says
An unhandled exception of type 'System.InvalidOperationException' occurred in dblayer.dll
Additional information: The ConnectionString property has not been initialized.
Can anyone help me out?
Solution 1: You need touse following statement to initilialise the connectionstring properly.
public string connectionString =ConfigurationManager.ConnectionStrings
[ConfigurationManager.AppSettings["myconnection"]].ConnectionString;
Solution 2:
Table is keyword hence you need to enclose it within the square brackets [].
Replace This:
string sql = "insert into Table(team1_name,team2_name)
values(#team1_name,#team2_name)";
With :
string sql = "insert into [Table](team1_name,team2_name)
values(#team1_name,#team2_name)";
Try This:
Connection String:
<configuration>
<connectionStrings>
<add name="conName" connectionString="Server=ServerName;initial catalog=DBName;User ID=sa;Password=sa123;"/> // SQL server Authentication
</connectionStrings>
<configuration>
public string connectionString = ConfigurationManager.ConnectionStrings["ConnectionName"].ConnectionString;
public int get_details(string team1_name, string team2_name)
{
SqlConnection con = new SqlConnection(connectionString);
string sql = "insert into Table(team1_name,team2_name) values(#team1_name,#team2_name)";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#team1_name", team1_name);
cmd.Parameters.AddWithValue("#team2_name", team2_name);
try
{
cmd.Connection = con;
con.Open();
return cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
}
}
I try to call function to select data from database,coz it will more efficient and i don't like to open connection and execute reader every time,have any solution can do like that?
this is my first method to select data from database,but will hit sql injection problem
protected void Button1_Click(object sender, EventArgs e)
{
Class1 myClass = new Class1();
lblAns.Text = myClass.getdata("Table1", "Student", "Student = '" + TextBox1.Text + "'");
}
public string getdata(string table,string field,string condition)
{
SqlDataReader rdr;
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True");
string sql = "select " + field + " from " + table + " where " + condition;
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
return "true";
}
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
}
finally
{
conn.Close();
}
return "false";
}
this is my second method but will hit error (ExecuteReader requires an open and available Connection. The connection's current state is closed.) at line (rdr = cmd.ExecuteReader();)
public string getdata(SqlCommand command,SqlConnection conn)
{
SqlDataReader rdr;
try
{
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd = command;
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
return "true";
}
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Select Error:";
msg += ex.Message;
}
finally
{
conn.Close();
}
return "false";
}
public SqlConnection conn()
{
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True");
return conn;
}
protected void Button1_Click(object sender, EventArgs e)
{
Class1 myClass = new Class1();
string strSql;
strSql = "Select student from Table1 where student=#stu";
SqlCommand command = new SqlCommand(strSql, myClass.conn());
command.Parameters.AddWithValue("#stu", TextBox1.Text);
myClass.getdata(command, myClass.conn());
}
have solution can use 1st method but will not hit the sql injection problem?
Use ALWAYS the second solution. The only way to avoid Sql Injection is through the use of parameterized queries.
Also fix the error on the second example. You don't associate the connection to the command, also it is a bad practice to keep a global object for the connection. In ADO.NET exist the concept of Connection Pooling that avoid the costly open/close of the connection while maintaining a safe Handling of these objects
public string getdata(SqlCommand command)
{
// Using statement to be sure to dispose the connection
using(SqlConnection conn = new SqlConnection(connectionString))
{
try
{
conn.Open();
cmd.Connection = conn;
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
return "true";
}
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Select Error:";
msg += ex.Message;
return msg;
}
}
return "false";
}