Hi everyone ı hade a bug about this methots ı use connection string a xml file. firt line is my xml file when ı run to code it's not
working ı think this code right but ı can't find where is the bug
this is connection string
<?xml version="1.0" encoding="utf-8" ?>
<conn>
<Dbconn>
<cstring>Server=DESKTOP-DSGBABB;Trusted_Connection=True ;database=master</cstring>
</Dbconn>
</conn>
this is my code
private void materialFlatButton1_Click(object sender, EventArgs e)
{
CreateDB();
}
public void CreateDB()
{
XmlTextReader reader = null;
reader = new XmlTextReader(filename);
reader.WhitespaceHandling = WhitespaceHandling.None;
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
if (reader.Name == "cstring")
{
conn = reader.ReadString();
}
}
using (connection = new SqlConnection(conn))
{
if (connection.State != ConnectionState.Open)
{
connection.Open();
}
str = "CREATE DATABASE uc ON PRIMARY " +
"(NAME = uc, " +
"FILENAME = 'C:\\uc.mdf', " +
"SIZE = 3MB, MAXSIZE = 10MB, FILEGROWTH = 10%) " +
"LOG ON (NAME = uc_Log, " +
"FILENAME = 'C:\\uc.ldf', " +
"SIZE = 1MB, " +
"MAXSIZE = 5MB, " +
"FILEGROWTH = 10%)";
connection.Close();
SqlCommand myCommand = new SqlCommand(str, connection);
try
{
connection.Open();
myCommand.ExecuteNonQuery();
MessageBox.Show("Veritabanı Başarıyla Oluşturuldu");
connection.Close();
}
catch (System.Exception ex)
{
lbls.Text = #"Error occured.
+ " + ex.Message.ToString();
}
connection.Close();
}
}
}
ı will wait for your help
Please try to change your connection string as follows:
Data Source=DESKTOP-DSGBABB;Initial Catalog=master;Integrated Security=True;
So the XML will be like below:
<?xml version="1.0" encoding="utf-8"?>
<conn>
<Dbconn>
<cstring>Data Source=DESKTOP-DSGBABB;Initial Catalog=master;Integrated Security=True;</cstring>
</Dbconn>
</conn>
It is much easier to use LINQ to XML API while dealing with XML.
Here is how to retrieve a connection string from the XML file.
Additionally, the SqlConnectionStringBuilder type will validate correctness of the connection string.
c#
void Main()
{
const string configFile = #"e:\Temp\configXMLFile.xml";
XDocument xdoc = XDocument.Load(configFile);
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.ConnectionString = xdoc.Descendants("Dbconn").Elements("cstring").FirstOrDefault().Value;
using (connection = new SqlConnection(conn))
{
...
}
}
Related
I'm working on an app with an Access 2010 db connection and I keep receiving OleDB error 80004005 and I can't figure out why.
const String conn = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=E:\OneDrive\Dropbox\SharpDevelop Projects\electronics inventory\electronics.mdb";
const String qCont = "select Section, Number, Stock from Container where Component = #IdComp order by Section, Number";
int oldParamSubcat = 0;
OleDbConnection connection = new OleDbConnection(conn);
void GrdCompCellClick(object sender, DataGridViewCellEventArgs e)
{
String IdComp = grdComp[grdComp.Columns["ID"].Index, grdComp.CurrentCell.RowIndex].Value.ToString();
try
{
grdSubcat.DataSource = null;
grdSubcat.Rows.Clear();
grdSubcat.Columns.Clear();
connection.Open();
OleDbCommand cmdDetail = new OleDbCommand();
cmdDetail.Connection = connection;
cmdDetail.CommandText = qDetail;
cmdDetail.Parameters.AddWithValue("#IdComp", Convert.ToInt32(IdComp));
txtDetails.Text = "";
OleDbDataReader rdDetail = cmdDetail.ExecuteReader();
rdDetail.Read();
txtDetails.Text = rdDetail["Component"].ToString() + "\r\n";
txtDetails.Text += rdDetail["Parameter"].ToString() + ": ";
txtDetails.Text += rdDetail["Val"].ToString() + "\r\n";
while(rdDetail.Read())
{
txtDetails.Text += rdDetail["Parameter"].ToString() + ": ";
txtDetails.Text += rdDetail["Val"].ToString() + "\r\n";
}
rdDetail.Close();
connection.Close();
connection.Open();
OleDbCommand cmdCode = new OleDbCommand();
cmdCode.Connection = connection;
cmdCode.CommandText = qCode;
cmdCode.Parameters.AddWithValue("#IdComp", Convert.ToInt32(IdComp));
txtDetails.Text += "\r\n";
OleDbDataReader rdCode = cmdCode.ExecuteReader();
while(rdCode.Read())
{
txtDetails.Text += rdCode["Seller"].ToString() + ": ";
txtDetails.Text += rdCode["Code"].ToString() + "\r\n";
}
rdCode.Close();
connection.Close();
connection.Open();
OleDbCommand cmdCont = new OleDbCommand();
cmdCont.Connection = connection;
cmdCont.CommandText = qCont;
cmdCont.Parameters.AddWithValue("#IdComp", Convert.ToInt32(IdComp));
txtDetails.Text += "\r\n";
OleDbDataReader rdCont = cmdCont.ExecuteReader(); ////////// here is where i receive the error ///////////////
while(rdCont.Read())
{
txtDetails.Text += "Container: ";
txtDetails.Text += rdCont["Section"].ToString() + "-";
txtDetails.Text += rdCont["Number"].ToString() + " = ";
txtDetails.Text += rdCont["Stock"].ToString() + " units\r\n";
}
rdCont.Close();
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
The rest of the code works perfectly, I only get the error on cmdCont.ExecuteReader();
The error message
If i execute the query in Access, it runs ok.
Any ideas are very much welcome.
Thanks.
The words Section, Number and Container are listed between the reserved keyword for MS-Access. You shouldn't use them in your table schema but if you really can't change these names to something different then you need to put them between square brackets
const String qCont = #"select [Section], [Number], Stock from [Container]
where Component = #IdComp order by [Section], [Number]";
Also you should use a more robust approach to your disposable objects like the connection, the commands and the readers. Try to add the using statement to your code in this way:
try
{
....
using(OleDbConnection connection = new OleDbConnection(......))
{
connection.Open();
....
string cmdText = "yourdetailquery";
using(OleDbCommand cmdDetail = new OleDbCommand(cmdText, connection))
{
.... // parameters
using(OleDbDataReader rdDetail = cmdDetail.ExecuteReader())
{
... read detail data ....
}
}
// here the rdDetail is closed and disposed,
// you can start a new reader without closing the connection
cmdText = "yourcodequery";
using(OleDbCommand cmdCode = new OleDbCommand(cmdText, connection))
{
.... parameters
using(OleDbReader rdCode = cmdCode.ExecuteReader())
{
// read code data...
}
}
... other command+reader
}
// Here the connection is closed and disposed
}
catch(Exception ex)
{
// any error goes here with the connection closed
}
I have been looking for a solution but I couldn't find anything.
I have to create a folder and after that I have to create a database in it by programatically. I have created folder and database but when I want to create a table in it, first I doesn't say anything (I guess it creates) but I cannot see the tables anywhere and if I will try for second time, it says 'There is already an object name like 'table_name' in the database.
And here is my code:
public void CreateFolder(string folderName)
{
int count = 0;
string path = "C:\\Users\\aabbccdd\\Documents\\";
string[] folders = Directory.GetDirectories(path);
foreach (var item in folders)
{
string dosyaAdi = item.Substring(path.Length);
if (dosyaAdi.Length >= folderName.Length)
{
if (folderName == item.Substring(path.Length, folderName.Length))
{
count = count + 1;
}
}
}
public void CreateSqlDatabase(string filename)
{
string databaseName = System.IO.Path.GetFileNameWithoutExtension(filename);
using (var connection = new System.Data.SqlClient.SqlConnection(
"Data Source=.\\sqlexpress;Initial Catalog=master; Integrated Security=true;User Instance=True;"))
{
try
{
try
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText =
String.Format("CREATE DATABASE {0} ON PRIMARY (NAME={0}, FILENAME='{1}')", databaseName, filename);
command.ExecuteNonQuery();
MessageBox.Show("Database başarılı bir şekilde oluşturuldu.", "Database", MessageBoxButtons.OK, MessageBoxIcon.Information);
btn_forward.Visible = true;
command.CommandText =
String.Format("EXEC sp_detach_db '{0}', 'true'", databaseName);
command.ExecuteNonQuery();
command.CommandText = String.Format("IF EXISTS (SELECT * FROM sysobjects WHERE name='cftc_fabrika') alter table cftc_fabrika alter column asuman varchar(100) ELSE create table cftc_fabrika(asuman varchar(100))");
command.ExecuteNonQuery();
}
}
catch (SystemException ex) // Change exception type based on your underlying data provider
{
if (ex.Message.ToLower().Contains("already exists. choose a different database name"))
{
var match = Regex.Match(ex.Message, "LDATABASE '(.*)' already exists.",
RegexOptions.IgnoreCase);
if (match.Success)
{
String dbFileName = match.Groups[1].Value;
Process p = new Process();
p.StartInfo.UseShellExecute = true;
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p.StartInfo.FileName = String.Format("{0}/Tools/SSEUtil.exe",
Environment.CurrentDirectory);
p.StartInfo.WorkingDirectory = Environment.CurrentDirectory;
p.StartInfo.Arguments = String.Format("-d \"{0}\"", dbFileName);
p.Start();
}
}
}
finally
{
if (connection.State == ConnectionState.Open)
{
connection.Close();
}
}
}
catch (Exception ex)
{
MessageBox.Show("Hata" + ex.ToString());
}
}
}
This way you can create the database and then create the table by using this database Name
String str;
SqlConnection myConn = new SqlConnection ("Server=localhost;Integrated security=SSPI;database=master");
str = "CREATE DATABASE MyDatabase ON PRIMARY " +
"(NAME = MyDatabase_Data, " +
"FILENAME = 'C:\\MyDatabaseData.mdf', " +
"SIZE = 2MB, MAXSIZE = 10MB, FILEGROWTH = 10%) " +
"LOG ON (NAME = MyDatabase_Log, " +
"FILENAME = 'C:\\MyDatabaseLog.ldf', " +
"SIZE = 1MB, " +
"MAXSIZE = 5MB, " +
"FILEGROWTH = 10%)";
SqlCommand myCommand = new SqlCommand(str, myConn);
try
{
myConn.Open();
myCommand.ExecuteNonQuery();
MessageBox.Show("DataBase is Created Successfully", "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString(), "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally
{
if (myConn.State == ConnectionState.Open)
{
myConn.Close();
}
}
For Table Do this:-
var commandStr= "If not exists (select name from sysobjects where name = 'Customer') CREATE TABLE Customer(First_Name char(50),Last_Name char(50),Address char(50),City char(50),Country char(25),Birth_Date datetime)";
using (SqlCommand command = new SqlCommand(commandStr, con))
command.ExecuteNonQuery();
Blog For you
I want to retrieve data from the server database using windows services on a text file?Can i do that?How will i do that?I mean i know to create a window service but i am confused with the SQL connection and file writing part where to execute it?i have tried something
class Program
{
static void Main(string[] args)
{
RunSchedule();
}
public static void RunSchedule()
{
string path = Path.GetFullPath("d:\\MyTest") + "\\" + DateTime.Now.ToString("MM_dd_yyyy_HH_mm") + "_Log.txt";
try
{
if (!File.Exists(path))
{
File.Create(path);
SqlConnection conn = new SqlConnection("Data Source=...;Initial Catalog=Test;User ID=s_a;Password=sa56ta112;");
String sql = #"SELECT Id,UserName, Email,Password,CreatedDate
FROM Register";
SqlCommand com = new SqlCommand();
com.CommandText = sql;
//com.Connection = conn;
conn.Open();
StreamWriter tw = File.AppendText("d:\\MyTest");
SqlDataReader reader = com.ExecuteReader();
tw.WriteLine("Id,UserName,Email,Password,CreatedDate");
while (reader.Read())
{
tw.Write(reader["Id"].ToString());
tw.Write(" , " + reader["UserName"].ToString());
tw.Write(" , " + reader["Email"].ToString());
tw.Write(" , " + reader["Password"].ToString());
tw.Write(" , " + reader["CreatedDate"].ToString());
}
tw.WriteLine(DateTime.Now);
tw.WriteLine("---------------------------------");
tw.Close();
reader.Close();
conn.Close();
}
}
catch (Exception ex)
{
string errorLogPath = #"D:\MyTest.txt";
File.AppendAllText(errorLogPath, Environment.NewLine + ex.Message);
}
}
}
am i doing it correct? Please guide me.
while (reader.Read())
{
row = new DataRow();
row.ItemArray = new object[reader.FieldCount];
reader.GetValues(row.ItemArray);
foreach (object item in row.ItemArray)
{
streamWriter.Write((string)item + "\t");
}
streamWriter.WriteLine();
}
If you get "Access to the path 'd:\MyTest' is denied." error than go to the txt file properties in the solution explorer and than change the Copy to output directory property from Do not copy into Copy if newer or Copy always
I'm completely new to database programming. I'm working with Visual Studio 2010 and want to create a database programmatically.
So far I've tried to connect to a SQL Server Compact Edition like this:
public class HistoryDBAccess
{
private SqlConnection conn = new SqlConnection();
public HistoryDBAccess()
{
conn.ConnectionString = #"Server=localhost;Integrated security=SSPI;database=master";
string str = "CREATE DATABASE MyDatabase ON PRIMARY " +
"(NAME = MyDatabase_Data, " +
"FILENAME = 'C:\\MyDatabaseData.mdf', " +
"SIZE = 2MB, MAXSIZE = 10MB, FILEGROWTH = 10%) " +
"LOG ON (NAME = MyDatabase_Log, " +
"FILENAME = 'C:\\MyDatabaseLog.ldf', " +
"SIZE = 1MB, " +
"MAXSIZE = 5MB, " +
"FILEGROWTH = 10%)";
SqlCommand myCommand = new SqlCommand(str, conn);
try
{
conn.Open();
myCommand.ExecuteNonQuery();
MessageBox.Show("DataBase is Created Successfully", "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString(), "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally
{
if (conn.State == System.Data.ConnectionState.Open)
{
conn.Close();
}
}
}
}
The connection in the Ctor fails with the message that a connection could not be established.
Using the database wizard with VS2010 is fine, but how I can see the SQLCe server under windows 7?
Is it somewhere under the control panel and do I need a default password in the connection string?
Many thanks,
Juergen
I think you should add a connection to your database in Your project using Server Explorer(or Database Explorer) Then check your Connection string.
It looks like you are trying to pass the con object before opening the connection.
So Try this and let me know.
public HistoryDBAccess()
{
conn.ConnectionString = #"Server=localhost;Integrated security=SSPI;database=master";
string str = "CREATE DATABASE MyDatabase ON PRIMARY " +
"(NAME = MyDatabase_Data, " +
"FILENAME = 'C:\\MyDatabaseData.mdf', " +
"SIZE = 2MB, MAXSIZE = 10MB, FILEGROWTH = 10%) " +
"LOG ON (NAME = MyDatabase_Log, " +
"FILENAME = 'C:\\MyDatabaseLog.ldf', " +
"SIZE = 1MB, " +
"MAXSIZE = 5MB, " +
"FILEGROWTH = 10%)";
conn.Open();
SqlCommand myCommand = new SqlCommand(str, conn);
try
{
myCommand.ExecuteNonQuery();
MessageBox.Show("DataBase is Created Successfully", "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString(), "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally
{
if (conn.State == System.Data.ConnectionState.Open)
{
conn.Close();
}
}
}
}
Once you create it, you're probably going to want to interact with it. You should consider using NHibernate. It has a feature called SchemaExport that can drop and create databases as much as you like.
Here's an example using SQL Express, but it's not much different to use Compact Edition. You can get NHibernate installed in your project by opening it in Visual Studio and clicking Project > Manage NuGet Packages, then searching All Online for NHibernate.
public class NHContext
{
protected static Configuration NHConfiguration;
protected static ISessionFactory SessionFactory;
public static void DropDatabase()
{
new SchemaExport(NHConfiguration).Drop(false, true);
}
public static void CreateDatabase()
{
new SchemaExport(NHConfiguration).Create(false, true);
}
protected static Configuration configureNHibernate()
{
var configure = new Configuration();
configure.SessionFactoryName("BuildIt");
configure.DataBaseIntegration(db =>
{
db.Dialect<MsSql2008Dialect>();
db.Driver<Sql2008ClientDriver>();//db.Driver<SqlClientDriver>();
db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
db.IsolationLevel = IsolationLevel.ReadCommitted;
db.ConnectionString = #"Data Source=.\SQLEXPRESS;Persist Security Info=True;Integrated Security=SSPI;Initial Catalog=NHibernate32Test;User Instance=False";
db.Timeout = 10;
// For testing
db.LogFormattedSql = true;
db.LogSqlInConsole = true;
db.AutoCommentSql = true;
});
return configure;
}
public static void Setup()
{
NHConfiguration = configureNHibernate();
HbmMapping mapping = getMappings();
NHConfiguration.AddDeserializedMapping(mapping, "NHibernate32Test");
SchemaMetadataUpdater.QuoteTableAndColumns(NHConfiguration);
SessionFactory = NHConfiguration.BuildSessionFactory();
}
}
I retrieve data from Oracle database and populate a gridview. Next, I try to run a query to select some data but I get an error.
Here is the code:
Db.cs:
public static OracleConnection GetConnection()
{
OracleConnection connection = null;
string connectionString = "Data Source=" + Database +
";User ID=" + UserID +
";Password=" + Password +
";Unicode=True";
try
{
connection = new OracleConnection(connectionString);
}
catch (OracleException ex)
{
throw ex;
}
return connection;
}
Parameters are sent from default.aspx.cs:
new Db(database, userID, password);
OracleConnection connection = Db.GetConnection();
main.aspx.cs retrieves all the data:
private OracleConnection connection = new OracleConnection();
private Select select = new Select();
protected void Page_Load(object sender, EventArgs e)
{
Response.Buffer = true;
if (Db.IsLoggedIn())
{
string selectCommand =
"SELECT " + Settings.TABLE + ".* FROM " + Settings.TABLE + " ORDER BY ";
foreach (string ob in Settings.OB) selectCommand += ob + ", ";
Session["Error"] = null;
connection = Db.GetConnection();
select = new Select(ddlBubID, ddlBusArea, ddlDrillSite, ddlWell, connection);
gvData.DataKeyNames = Settings.PK;
gvData.SelectedIndex = -1;
DS.ConnectionString = connection.ConnectionString;
DS.SelectCommand = selectCommand.Remove(selectCommand.Length - 2, 2);
DS.ProviderName = Settings.PROVIDER_NAME;
PopulateFooter(gvData.FooterRow);
}
else
{
Session["Error"] = Settings.ERROR_MESSAGE[0, 0];
Response.Clear();
Response.Redirect("default.aspx");
}
}
public string ToolTip(string column)
{
string value = "";
OracleCommand cmd = new OracleCommand();
cmd.Connection = connection;
cmd.CommandText = "SELECT DISTINCT COMMENTS " +
"FROM SYS.ALL_COL_COMMENTS " +
"WHERE (TABLE_NAME = 'CTD_PROBLEM_EDIT_V') " +
"AND (COLUMN_NAME = " + column + ")";
cmd.CommandType = CommandType.Text;
OracleDataReader reader = cmd.ExecuteReader(); // I get an error here
reader.Read();
value = reader["COMMENTS"].ToString();
reader.Close();
return value;
}
protected void gvData_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
for (int i = 1; i < e.Row.Cells.Count; i++)
{
try
{
LinkButton lb =
(LinkButton)gvData.HeaderRow.Cells[i].Controls[0];
lb.ToolTip = ToolTip(lb.Text);
/* Blah Blah*/
}
catch { }
}
if (e.Row.RowType == DataControlRowType.Footer)
PopulateFooter(e.Row);
}
ToolTip(); throws an error:
Invalid operation. The connection is closed.
EDIT:
This would have been helpful:
Static Classes and Static Class Members
Might not be the problem but this looks weird:
new Db(database, userID, password);
OracleConnection connection = Db.GetConnection();
GetConnection is a static method and thus it does not see any member attributes you might be setting in the constructor (unless they are static as well). If they are all static, consider refactoring your code to use the singleton pattern as it is more readable.
Another thing is that the connection attribute is a member of the page class which is generated for each request (not per application). This means you need either create a new connection in ToolTip method (and any other method that accesses the database) or make the connection attribute static to make it per-application.
Try 2 things:
1.. For your ToolTip() method, the value column to compare for COLUMN_NAME will need to be wrapped properly with single quotes indicating a string/varchar literal value. Likely it's evaluating to COLUMN_NAME = foo when it should be COLUMN_NAME = 'foo'.
cmd.CommandText = "SELECT DISTINCT COMMENTS " +
"FROM SYS.ALL_COL_COMMENTS " +
"WHERE (TABLE_NAME = 'CTD_PROBLEM_EDIT_V') " +
"AND (COLUMN_NAME = '" + column + "')";
2.. Try wrapping your ad-hoc SQL statements in BEGIN and END
3.. Consider refactoring your string building for your SELECT and dynamic ORDER BY clause. That you're doing it on the SelectCommand many lines below isn't obvious to the casual observer or maintainers later in its life.
string selectCommand = string.Format("SELECT {0}.* FROM {0} ORDER BY {1}"
,Settings.TABLE
,string.Join(",",Settings.OB));