Pivot Table import .sql using dev express - c#

I have a pivot table using windows form application
I want to replace the data in pivot table with import data using .sql
I have tried this code
private void btnSelectFile_ItemClick(object sender,DevExpress.XtraBars.ItemClickEventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "Text files | *.sql";
if (dlg.ShowDialog() == DialogResult.OK)
{
string fileName;
fileName = dlg.FileName;
}
string ConnString = "server=localhost; user id=root; password=; database=db;persist security info=true;";
DataTable Data = new DataTable();
using(SqlConnection connect = new SqlConnection(ConnString))
{
connect.Open();
SqlCommand cmd = new SqlCommand(#"SELECT * FROM [dataGridView1_Data$]", connect);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(Data);
connect.Close();
}
}
but the connection error
System.Data.SqlClient.SqlException: 'A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)'

Start by connecting to the database from visual studio directly. Your connection string looks incorrect.
string ConnString = "server=localhost; user id=root; password=; database=db;persist security info=true;";
I do not believe SQL Server allows empty passwords anymore.

Related

After registering to my website instead of inserting the data to the sql server, an error message appears

In my asp website i have a register form that sends data to the database.
When a user enters his data, after submitting, an error is appeared that says:
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
This is the code:
signup.aspx.cs-
protected void submit_Click(object sender, EventArgs e)
{
string name = Request.Form["name"];
string email = Request.Form["email"];
string password = Request.Form["password"];
string fileName = "Database.mdf";
string sql = "INSERT INTO UserInfo VALUES('" + name + "','" + email + "','" + password + "')";
MyAdoHelper.DoQuery(fileName,sql);
}
MyAdoHelper.DoQuery-
public static void DoQuery(string fileName, string sql)
{
SqlConnection conn = ConnectToDb(fileName);
conn.Open();
SqlCommand com = new SqlCommand(sql, conn);
com.ExecuteNonQuery();
com.Dispose();
conn.Close();
}
MyAdoHelper.ConnectToDb-
public static SqlConnection ConnectToDb(string fileName)
{
string path = HttpContext.Current.Server.MapPath("App_Data/");
path += fileName;
//string path = HttpContext.Current.Server.MapPath("App_Data/" + fileName);
string connString = #"Data Source=.\SQLEXPRESS;AttachDbFilename=" +
path +
";Integrated Security=True;User Instance=True";
SqlConnection conn = new SqlConnection(connString);
return conn;
}
My database name is Database.mdf and its under App_Data Folder
Could anyone tell me what is the problem?
Thx !
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible.
Above error message clearly suggest that the instance name ".\SQLEXPRESS" is wrong. Please first confirm the instance name.
By the word "registering" I guess you means "Hosted in a webserver". IN that case the connection string most probably won't work that way. We can find the connection string for the SQL server in you hosting providers control panel. Or you can ask them for connection string and mention them that you are using a SQL DB Local file which will be attached with the application. As an example you can provide them your current connection string.

My database system cannot find the file specified in asp.net

I am trying to retrieve data from a database with the following code:
public partial class populate : System.Web.UI.Page
{
SqlConnection scon = new SqlConnection("Data Source = localhost; Integrated Security = true; Initial Catalog = populate");
protected void Page_Load(object sender, EventArgs e) {
StringBuilder htmlString = new StringBuilder();
if(!IsPostBack)
{
using (SqlCommand scmd = new SqlCommand())
{
scmd.Connection = scon;
scmd.CommandType = CommandType.Text;
scmd.CommandText = "SELECT * FROM populate";
scon.Open();
SqlDataReader articleReader = scmd.ExecuteReader();
htmlString.Append("'Populate page:'");
if (articleReader.HasRows)
{
while (articleReader.Read())
{
htmlString.Append(articleReader["dateTime"]);
htmlString.Append(articleReader["firstName"]);
htmlString.Append(articleReader["lastName"]);
htmlString.Append(articleReader["address"]);
htmlString.Append(articleReader["details"]);
}
populatePlaceHolder.Controls.Add(new Literal { Text = htmlString.ToString() });
articleReader.Close();
articleReader.Dispose();
}
}
}
}
}
It's throwing an error:
The system cannot find the file specified
I am wondering if someone can show me where the error is or guide me through debugging this. Thanks in advance.
(update): More specifically, the scon.Open() is causing the error:
Message=A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
This looks easy enough to fix, but I'm not very good with the database. Any help will be appreciated.
I don't know what SQL Server edition you have installed, and what you called it (as an instance name) .....
Go to Start > SQL Server > Configuration Tools > Configuration Manager; under SQL Server Services, search for the SQL Server service - what is it's name??
If it's SQL Server (SQLEXPRESS), then that means you have the Express edition, with an instance name of SQLEXPRESS - change your connection string to:
Data Source=.\SQLEXPRESS;Initial Catalog=populate;Integrated Security=true;
If it's SQL Server (MSSQLSERVER) then you should be fine really - you have an unnamed, default instance ....

ConnectionString for SQL Server

I have xampp installed in my computer. I am trying to access data with ADO.Net. The connection string I am using is given below:
string connectionString = "Server = localhost; Database = magento; User Id = magento; Password = abcd;";
SqlConnection con = new SqlConnection(connectionString);
string cmdString = "SELECT date_added,title,description,url FROM adminnotification_inbox";
SqlDataAdapter da = new SqlDataAdapter(cmdString, con);
ds = new DataSet();
da.Fill(ds,"prog");
dt = ds.Tables["prog"];
currRec = -1;
totalRec = dt.Rows.Count;
button3.Enabled = true;
I am able to log in with the above user id and password in phpmyadmin, but cannot access the database with the above connection string. please help. Thanks in advance.
MySQL has its own ADO.NET connector: http://dev.mysql.com/downloads/connector/net/6.6.html#downloads
If you use that, you can create a MySqlConnection: http://dev.mysql.com/doc/refman/5.5/en/connector-net-tutorials-intro.html
The basic SqlConnection is used for Microsoft's own SQL Server products.
9-22-14 - Hope others see this if you don't:
You need a driver in your connect string I believe. "MySQL ODBC 3.51 Driver" is the Window's driver name.
string connectionString ="Driver={MySQL ODBC 3.51 Driver}; SERVER= .... ok put the rest of your connect string here.
Note: this is the string to connect to a MySQL db using MS Access VBA:
Dan

C# How to Read from MySQL database Wampserver

I am trying to read a table from a Wampserver using this, but I get an error message "A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)"
When I ping localhost all the pings are received. Is this code correct?
private void button5_Click(object sender, EventArgs e)
{
SqlConnection myConnection = new SqlConnection("user id=root;" +
"password=pass;server=localhost;" +
"database=database; " +
"connection timeout=10");
string query = "select * from table";
SqlCommand cmd = new SqlCommand(query, myConnection);
myConnection.Open(); // the error
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(tabelsql);
myConnection.Close();
da.Dispose();
}
If you're using a WampServer than that means you're using MySQL, right?
MySQL and SQL Server are not the same. SQLConnection, SQLCommand and SQLDataAdapter are used to connect to SQL Server (the RDBMS from Microsoft), not MySQL.
To access a MySQL database from .NET you can use the MySQL Connector.
SqlCommand and SqlDataAdapter are part of the MS SQL ADO.NET native client and can only be used for MS Sql Server. WAMP appears to include MySql. For that, you'll likely want to use the MySql ADO.NET driver found here. And this article provides some sample code for reading MySql data utilizing a DataReader.
To Read a single table from MySql database which is in wamp server.
If wamp-server is in localhost then,
Add reference ..
using MySql.Data.MySqlClient;
And after this..
write below public partial class this connection query..
MySqlConnection cn = new
MySqlConnection
("server=localhost;database=database;userid=root;password=;charsetutf8;");
write this GetData() in your form load event or below InitializeComponent...
private void GetData()
{
cn.Open();
MySqlDataAdapter adp = new MySqlDataAdapter("SELECT * from
tablename", cn);
DataTable dt = new DataTable();
adp.Fill(dt);
dataGridViewName.DataSource = dt;
adp.Dispose();
cn.Close();
}

How can I connect to a SDF database? No connection string I try seems to work

I've tried literally 50+ different attempts at my connection string for my local database and nothing seems to work. I'm essentially just trying to open a connection the database file so I can dump in the data I've pulled out of my excel spreadsheet. I'm using Visual C# making an offline winform application.
No matter what connection string I try in my app.config, it always fails when it tries to write "dReader" to the database.
The error is usually this depending on what string I try:
"A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)"
I've gone through many online examples and resources and none seem to work. I'm hoping someone here can point out why it's failing.
Here is my app.config in its latest form:
<connectionStrings>
<add name="DDP_Project.Properties.Settings.DDP_DatabaseConnectionString"
connectionString="Data Source=E:\Other DDP Projects\DDP_Project_SDF\DDP_Project\DDP_Database.sdf;"
providerName="Microsoft.SqlServerCe.Client.3.5" />
</connectionStrings>
Here is my form code:
private void Profiles_Click(object sender, EventArgs e)
{
profilesDialog.FileName = "[YOUR_UPLOAD_FILE_HERE]";
var result = profilesDialog.ShowDialog();
if (result == DialogResult.OK)
{
HandleFileSelection();
}
}
private void HandleFileSelection()
{
var file = profilesDialog.FileName;
// Create a connection to the file datafile.sdf in the program folder
string dbfile = new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).DirectoryName + "\\DDP_Database.sdf";
SqlCeConnection connection = new SqlCeConnection("datasource=" + dbfile);
string strConnection = ConfigurationManager.ConnectionStrings["DDP_Project.Properties.Settings.DDP_DatabaseConnectionString"].ConnectionString;
//Create connection string to Excel work book
string excelConnectionString = string.Format(
#"Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=""{0}"";
Extended Properties=""Excel 8.0;HDR=YES;""", file
);
//Create Connection to Excel work book
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
OleDbCommand cmd = new OleDbCommand("SELECT [ID],[STATUS],[FAN_NUM],[PROFILE_NAME],[DESTINATION_HOST],[USER_ID],[USER_PASSWORD],[PROTOCOL],[PORT],[PATH],[CONTACT_NAME],[CONTACT_EMAIL],[CONTACT_PHONE],[CONTACT_ALT_PHONE],[CONTACT_CITY],[CONTACT_STATE],[CONTACT_CONTACT_TIME] FROM [Sheet1$]", excelConnection);
excelConnection.Open();
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection);
sqlBulk.DestinationTableName = "Profiles";
sqlBulk.ColumnMappings.Add("ID", "ID");
sqlBulk.ColumnMappings.Add("STATUS", "STATUS");
sqlBulk.ColumnMappings.Add("FAN_NUM", "FAN_NUM");
sqlBulk.ColumnMappings.Add("PROFILE_NAME", "PROFILE_NAME");
sqlBulk.ColumnMappings.Add("DESTINATION_HOST", "DESTINATION_HOST");
sqlBulk.ColumnMappings.Add("USER_ID", "USER_ID");
sqlBulk.ColumnMappings.Add("USER_PASSWORD", "USER_PASSWORD");
sqlBulk.ColumnMappings.Add("PROTOCOL", "PROTOCOL");
sqlBulk.ColumnMappings.Add("PORT", "PORT");
sqlBulk.ColumnMappings.Add("PATH", "PATH");
sqlBulk.ColumnMappings.Add("CONTACT_NAME", "CONTACT_NAME");
sqlBulk.ColumnMappings.Add("CONTACT_EMAIL", "CONTACT_EMAIL");
sqlBulk.ColumnMappings.Add("CONTACT_PHONE", "CONTACT_PHONE");
sqlBulk.ColumnMappings.Add("CONTACT_ALT_PHONE", "CONTACT_ALT_PHONE");
sqlBulk.ColumnMappings.Add("CONTACT_CITY", "CONTACT_CITY");
sqlBulk.ColumnMappings.Add("CONTACT_STATE", "CONTACT_STATE");
sqlBulk.ColumnMappings.Add("CONTACT_CONTACT_TIME", "CONTACT_CONTACT_TIME");
sqlBulk.WriteToServer(dReader);
sqlBulk.Close();
excelConnection.Close();
}
private void profilesDialog_FileOk(object sender, EventArgs e)
{
}
}
}
Try this...
First:
Create first a test method which you may check if you can connect to sqlcedatabase.
private void testconnection()
{
string strConnection = ConfigurationManager.ConnectionStrings["DDP_Project.Properties.Settings.DDP_DatabaseConnectionString"].ConnectionString;
using (var conn = new SqlCeConnection(string.Format("Data Source={0};Max Database Size=4091;Max Buffer Size = 1024;Default Lock Escalation =100;", strConnection)))
{
conn.Open();
try
{
//your Stuff
}
catch (SqlCeException)
{
throw;
}
finally
{
if (conn.State == ConnectionState.Open) conn.Close();
}
}
}
Second:
Just Load your excel file Data into a Datatable and use foreach then save it on your sql ce database file..
//Something like
//oledbcon
//oledb dataadapter
//datatable
// dapt.Fill(dt);
foreach(DataRow excel in dt.Rows)
{
ceCmd.Parameters.AddWithValue("ID",excel["ID"]);
ceCmd.ExecuteNonQuery();
}
Regards
I think the problem you are seeing is that you are trying to use a SqlConnection to connect to a SQL Compact database. The .sdf is a compact database and you have to use the SqlCeConnection to connect to it. You create the connection using this but then you don't use it. Instead you pass in the connection string to the SqlBulkCopy object which implicitly creates a SqlConnection from that string. I'm assuming it is on that line where you are getting the error. If you notice the namespace of the SqlBulkCopy is System.Data.SqlClient. The reason you are seeing the error is that its trying to go through SQL Server to make the connection and cannot resolve your connection string to a SQL Server database. Unfortunately, I don't think the System.Data.SqlServerCe has the equivalent to the SqlBulkCopy. Stick to using classes in System.Data.SqlServerCe and things should work as expected. You just will have to do the processing in a more manual fashion.
According to this post, SqlBulkCopy isn't supported with SqlCe.

Categories

Resources