Connecting to mysql on 000webhost using C# - c#

Im simply just trying to read what there is in the batabase on to a console but i always get an exception on the conn.Open() line. Here is all the code:
SqlConnectionStringBuilder conn_string = new SqlConnectionStringBuilder();
conn_string.DataSource = "mysql14.000webhost.com"; // Server
conn_string.UserID = "a7709578_codecal";
conn_string.Password = "xxxxx";
conn_string.InitialCatalog = "a7709578_codecal"; // Database name
SqlConnection conn = new SqlConnection(conn_string.ToString());
conn.Open();
SqlCommand cmd = new SqlCommand("Select name FROM Users");
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("{1}, {0}", reader.GetString(0), reader.GetString(1));
}
reader.Close();
conn.Close();
if (Debugger.IsAttached)
{
Console.ReadLine();
}

You need to build the connection string manually or use MySqlConnectionStringBuilder. MySql uses a different format than SQL Server and the SqlConnectionStringBuilder that you're using. You also need to use a MySQL library, SqlConnection, SqlCommand, etc are all build specifically for SQL Server.
MySQL connectors

For MySQL database you are using wrong provider. Those classes you have used in posted code are for SQL Server. Your code should look like below with MySQL provider related classes
MySqlConnectionStringBuilder conn_string = new MySqlConnectionStringBuilder();
conn_string.Server = "mysql14.000webhost.com";
conn_string.UserID = "a7709578_codecal";
conn_string.Password = "xxxxxxx";
conn_string.Database = "a7709578_codecal";
using (MySqlConnection conn = new MySqlConnection(conn_string.ToString()))
Check Related post in SO
Also to point out, you are selecting only one column from your table as can be seen
new SqlCommand("Select name FROM Users");
Whereas trying to retrieve two column value, which is not correct
Console.WriteLine("{1}, {0}", reader.GetString(0), reader.GetString(1))

000webhost free servers does not allow external connections to the server database.
You can only use your database from your PHP scripts stored on the server.
You can get data from database using PHP and it will return.So i advice to you using php from C# like api.

Related

Can not retrieve a list of tables from an Oracle database - conn.GetSchema("Tables")

I need to retrieve the list the tables in an Oracle database that is defined by a DSN that is using the Oracle ODBC driver.
However, OdbcConnection.GetSchema("Tables") throws an exception ERROR [HYT00] [Oracle][ODBC][Ora]ORA-01013: user requested cancel of current operation\n or ORA-00604: error occurred at recursive SQL level 1 after about 30 seconds.
using (OdbcConnection connection = new OdbcConnection("Driver={Oracle in OraDB18Home1};Dbq=XE;Uid=system;Pwd=mypassword;"))
{
connection.Open();
//Also unsuccessful with "Views" and "Columns", but works with "DataTypes" and "Restrictions"
DataTable schema = connection.GetSchema("Tables");
}
The database is newly installed and is not too big.
I can call GetSchema() without parameters to successfully retrieve all supported schema collections.
I can also successfully run a query against my database:
OdbcCommand command = new OdbcCommand("SELECT * FROM vendors")
{
Connection = connection
};
OdbcDataReader reader = command.ExecuteReader();
You should stop using ODBC. Use ODP.NET - this is gold standard Oracle .NET provider. And use "Managed" version, i.e. Oracle.ManangedDataAccess. This code below will work fine
var conn = new OracleConnection("Data Source=server:1521/sid;password=pwd;user id=usr");
conn.Open();
var tbl = conn.GetSchema();
conn.Close();
Consile.WriteLine(tbl.Rows.Count.ToString());

Login Failed for User when trying to Open() a SqlConnection in C#

I'm using Sql Server 2017 and Visual Studio 2017. I transferred my database from my PC to my friend's laptop using Generate Scripts. I use the following code in my friend's laptop when trying to connect to said database in the laptop:
using (SqlConnection sqlCon = new SqlConnection(#"Data Source = (local); Initial Catalog = PresentasiDB; Integrated Security = True; Trusted_Connection = True;"))
{
DataTable orderTable = new DataTable();
SqlDataAdapter sqlda;
string insertOrder = "INSERT INTO \"Order\" DEFAULT VALUES";
using (SqlCommand newOrder = new SqlCommand(insertOrder, sqlCon))
{
sqlCon.Open();
newOrder.ExecuteNonQuery();
}
sqlda = new SqlDataAdapter("SELECT TOP 1 * FROM \"Order\" ORDER BY OrderID DESC", sqlCon);
sqlda.Fill(orderTable);
orderID = Convert.ToInt32(orderTable.Rows[0][0]);
}
However, this failed. The failure occurred in the sqlCon.Open() part. I've tried using SQL Server login Authentication and Windows Authentication. Both failed. Someone, please help me.
In the data source you need to specify server name you use to connect to sql server.
As shown in the screen the datasource here is "gaurav.goel
Try your connecting string something like this (for sa login)
string connstr = userid=sa;password=sapassword;server=localhost,1433;database=PresentasiDB;Trusted_Connection=no
To test it did you try entering the server as 'localhost' from management studio?

How to connect SQLite with my C# application

i have a problem with making a local database into my c# project and creating it..
I tried first with making a Microsoft Sql Server but the problem is that i need to make app which should run on every pc. The app should input data from user , and collect it to the database, and on every start of program, the database should be filled with the leftover of earlier input.. What you suggest me to do?
First to connect your c# application with sqlite you should start with getting connection string
private static string executableLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
private static string oldconnectionstring = Path.Combine(executableLocation, "YourDB.db");
private static string connectionString = "Data Source =" + oldconnectionstring.ToString();
After getting connection, to add your input to database follow below steps
using (SQLiteConnection conn = new SQLiteConnection(connectionString))
{
//Open connection to DB
conn.Open();
//Query to be fired
string sql = "Your Query to insert rows";
//Executing the query
using (SQLiteCommand cmd = new SQLiteCommand(sql, conn))
{
//Executing the query
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
//Close connection to DB
conn.Close();
}

.Net C# how to connect to external SQL Server database ? OleDb or other?

Hi I would like to know how I should connect to the external SQL Server database in C# , .NET ?
For example if I have there parameters :
SQL info
Url to get to database (throughout browser also): Sqlweb.companyname.com
Database username: username
Server: Dcms-xxx
Databasename: databaseName
Databasepassword: password
?
I know how to connect to internal : Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + System.AppDomain.CurrentDomain.BaseDirectory + "..\\Files\\MapPlaces\\Database.mdb;";
But what about external ?
I have tried :
string nowConString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Sqlweb.companyname.com;Initial Catalog = databaseName; User Id = Username; Password = Password;";
System.Data.OleDb.OleDbConnection dbcon = new System.Data.OleDb.OleDbConnection(nowConString);
string sql = "SELECT * FROM XXXTable";
dbcon.Open();
System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand(sql, dbcon);
System.Data.OleDb.OleDbDataReader reader;
reader = cmd.ExecuteReader();
ScriptStuff.Append("Reader created!<br/>");
while (reader.Read())
{
string companyName = reader.GetValue(1).ToString();
ScriptStuff.Append(companyName+"<br/>");
}
Did not work ! Thank you for your help !
Edited from comments:
Yes that was one my mistake, thanks. Since first one was access and YES second is SQL Server. And it is SQL Server 2005. But I am new to .net and all that... I have found first one and second one in that connectionstring.com but I could not find or understand how to use that for this one ...
Could you help, and just post hole connection ? Thanks – Vilius 7 mins ago
I mean do I still need to use OleDB ? should there be "Provider=Microsoft.Jet.OLEDB.4.0;" in that connection string ? Where do i post what (server (that Dcms-xxx), or url of the sql server (sqlweb.companyname.com))? THANKS FOR YOUR HELP ! –
I would add a connectionString to my app/web.config.
<connectionStrings>
<add name="AspnetdbConnectionString"
connectionString="Data Source=<databaseadress>;Initial Catalog=<database>;User Id=<user>;Password=password>"
providerName="System.Data.SqlClient"
/>
</connectionStrings>
The above example is how you specify an connectionstring for a MSSQL connection, and below a way to use this connectionstring.
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["AspnetdbconnectionString"].ConnectionString))
{
cn.Open();
using (SqlCommand cm = cn.CreateCommand())
{
cm.CommandType = CommandType.Text;
cm.CommandText = "SELECT * FROM ...";
using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
{
while (dr.Read())
{
// do stuff
}
}
}
}
Are you sure that it's a SQL Server database that you are trying to connect to?
Your "internal" example connects to a Microsoft Access database (OLEDB provider and database file extension .mdb)
If your external database is really a SQL Server database, the recommended way is using SqlConnection, SqlDataReader and so on instead of OleDbConnection etc.
Or, if you really want to use OleDb, you need a different connection string.
See connectionstrings.com (for SQL Server 2008, 2005 or 2000, depending what you're trying to connect to).
I would highly recommend taking a look at:
http://www.connectionstrings.com/
It's a quick, "in you face" treatment of the subject of connection strings for all major databases.

is there anyway to connect to sybase from c# without having to add a ODBC DSN connection in control panel

I am looking for a way to connect to sybase from C# without having to setup an ODBC DSN connection locally on the machine.
Is this possible? I tried all of these different connection strings:
static private DataTable Run(string sql)
{
var conn = new OdbcConnection();
const string CONN_STRING2 =
"Data Source='[myServer]';Port=5020;Database=[dbName];Uid=[user];Pwd=[pwd];";
const string CONN_STRING1 =
"Provider=Sybase.ASEOLEDBProvider.2;Server Name=[myServer];Server Port Address=5020;Initial Catalog=[dbName];User ID=[user];Password=[pwd];";
conn.Open();
var da = new OdbcDataAdapter { SelectCommand = conn.CreateCommand() };
da.SelectCommand.CommandText = sql;
var dt = new DataTable();
da.Fill(dt);
da.Dispose();
conn.Close();
return dt;
}
But I got an error stating:
{"ERROR [IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified"}
You are using var conn = new OdbcConnection(). That is why you are getting the error.
You will need to use a sybase oledb client library. I don't know sybase at all but last I heard one needed to purchase a third-party provider. This was almost three years ago so they may have one by now.
You would then need to do something like var connection = new ASEConnection().
Download the DLL from the following link:
Sybase library
Use this library for connection:
ASEconnection connection = new AseConnection();
Use specific ADO.Net data provider stright from manufacturer (SAP now own sybase). I think you can manage to create a connection string yourself using this reference. For example:
var connStr = #"Data Source=\\myserver\myvolume\mypat\mydd.add;User ID=myUsername;
Password=myPassword;ServerType=REMOTE;"
using (ASEConnection conn = new AseConnection(connStr)) {
// use conn
}
Same informaton can be obtained from documentation mentioned earlier.

Categories