SqlConnection con = new SqlConnection(#"server=MOON\SQLEXPRESS;Initial Catalog=Moon;Integrated Security=True");
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
// Get our button from the layout resource,
// and attach an event to it
Button button = FindViewById<Button>(Resource.Id.btnsubmit);
button.Click += button_Click;
}
void button_Click(object sender, EventArgs e)
{
try
{
EditText etuser = FindViewById<EditText>(Resource.Id.txtuser);
EditText etpass = FindViewById<EditText>(Resource.Id.txtpass);
con.Open();
SqlCommand cmd = new SqlCommand("insert into Login values('" + etuser.Text + "','" + etpass.Text + "')", con);
cmd.ExecuteReader();
con.Close();
}
catch(Exception ex)
{
string result;
result = ex.Message;
Toast.MakeText(this, result, ToastLength.Short).Show();
}
}
Please help me out I want to insert a record but an error shows up
Could not resolve host MOON
Please help me out. I am using local database and my server name is also MOON\SQLExpress.
Create a (selfhosted) webservice on your sqlserver computer.
Run your service as admin
Create a service consuming class with SlSvcUtil
(Download & Install from: https://www.microsoft.com/de-DE/download/details.aspx?id=28359)
Put this class in your xamarin project
consume the service in your app
Related
I have a wpf application that is connected to my database which was created in microsoft SQL server Management using this:
private SqlConnection connect()
{
con = new SqlConnection();
con.ConnectionString = "Server=LAPTOP-1B0SDCU1 ;Database=project;User ID=sa;Password=123;Trusted_Connection=true;Integrated Security=false";
return con;
}
and added my data in a table called material as such
private void insertdata(object sender, RoutedEventArgs e)
{
connect();
con.Open();
string material = materialfield.Text;
string saved = "INSERT INTO materialtable(material) VALUES ('" + material + "')";
SqlCommand com = new SqlCommand(saved, con);
com.ExecuteReader();
viewdetails();
MessageBox.Show("record is added");
}
here my server is my own computer. Now I want to give this application to my client along with the database so that they can add details into the database and those details will only be stored on their laptop, but I do not know how to. Can someone please help.
I have a SQL Server .MDF database file that contains data and tables that I need to load into my project and add or update that data so when I attach the file and run my program on a second PC that has SQL Server already installed, I get error that database is not found!
Note1: database was created in SQL Server 2012 local host server and Windows authentication mode.
I am using this code for loading and using database :
SqlConnection c = new SqlConnection(#"Data Source=.;Initial Catalog=db1;Integrated Security=True");
private void Form1_Load(object sender, EventArgs e)
{
String str;
SqlConnection myConn = new SqlConnection(#"Data Source=.;Initial Catalog=db1;Integrated Security=True");
str = "CREATE DATABASE db1";
SqlCommand myCommand = new SqlCommand(str, myConn);
try
{
myConn.Open();
myCommand.ExecuteNonQuery();
MessageBox.Show("First db is Created", "MyProgram", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (System.Exception ex)
{
// MessageBox.Show("DB is exist");
}
finally
{
if (myConn.State == ConnectionState.Open)
{
myConn.Close();
}
}
using (SqlConnection con = new SqlConnection(#"Data Source=.;Initial Catalog=db1;Integrated Security=True"))
{
try
{
//Open.the SqlConnection;
con.Open();
//The following code uses a SqlCommand based on the SqlConnection
using (SqlCommand command = new SqlCommand("CREATE TABLE contents(id int IDENTITY(100, 1),Name char(50) NOT NULL,Lastname char(50) NOT NULL,Number char(50) ,Area nvarchar(50) ,Date nvarchar(50)NULL,Duration nvarchar(MAX),description nvarchar(MAX),gender nvarchar(50),number2 nvarchar(50),DT datetime NULL);", con))
command.ExecuteNonQuery();
}
catch (Exception ex)
{
//MessageBox.Show("Tables created");
}
}
}
Load table
private void button4_Click(object sender, EventArgs e)
{
SqlDataAdapter a = new SqlDataAdapter("select * from contents", c);
DataTable t = new DataTable();
a.Fill(t);
dataGridView1.DataSource = t;
dataGridView1.FirstDisplayedScrollingRowIndex = dataGridView1.RowCount - 1;
dataGridView1.AutoResizeColumns();
}
But it's not very unique and useful the db will be moved every day to another PC and it must load perfectly also I have some table in SQL file that are static and their is no need to code for them, I want to just use them as resource. Also I heard about some method that embedded or local db can be used as db in app data folder and can be moved with app wisely so I need some help here. Thanks
instead of creating a raw db everytime, you can use your mdf file as source,like below
Create database dbname
On
(
Filename= 'path where you copied mdf file'
)
For attach;
I am using a connection class for my connection and then I call the class for connecting.
After I use the connection several times it freezes and then gives a error. It seems I have got to many connections open at the same time I can't figure out how tho close the open connections. If that is the real problem.
MyConnection class:
public class MyConnection
{
private SqlConnection _con;
public SqlCommand Cmd;
private SqlDataAdapter _da;
private DataTable _dt;
public MyConnection()
{
_con = new SqlConnection("Data Source=192.168.1.12\\grs;Initial Catalog=BGI;Persist Security Info=True;User ID=awplanung;Password=pass");
_con.Open();
}
public void SqlQuery(string queryText)
{
Cmd = new SqlCommand(queryText, _con);
}
public DataTable QueryEx()
{
_da = new SqlDataAdapter(Cmd);
_dt = new DataTable();
_da.Fill(_dt);
return _dt;
}
public void NonQueryEx()
{
Cmd.ExecuteNonQuery();
}
}
And now I call this connection from my forms: like this one.
MyConnection con = new MyConnection();
con.SqlQuery("SELECT ARartikelnr ,ARartikelbezeich, ARartwarengruppe, ARanzahleinheiten, ARinhalteinheiten, ARanzgebindepal FROM BGARTIKEL where ARartikelnr BETWEEN '" + textBox2.Text + "' and '" + textBox3.Text + "' order by ARinhalteinheiten, ARartwarengruppe");
dt = con.QueryEx();
Each time I open a new form I make a
MyConnection con = new MyConnection();
and make many similar
con.SqlQuery("Select string")
After I open a second form it freezes when I do a new long select. What is strange is that I have used these 2 forms without problems, but in the first one I made a datagrid fill with a button. and now i changed if to fill directly from the form load. and when i go to the next form i cant fill my other datagrid on the new form giving that error.
Error:
Timeout expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.
Make your MyConnection class disposable. And dispose it when you are done with data.
implement IDisposable interface on class
(public class MyConnection : IDisposable)
implement Dispose method where dispose your connection
public void Dispose()
{
_con.Dispose();
}
and use it like this
using(MyConnection con = new MyConnection())
{
con.SqlQuery("...");
dt = con.QueryEx();
}
I've been working on a website using ASP.NET MVC, and I have this page in the website where you can directly send the a email form to a specific email address. Before I don't have database for the form, and it's working perfectly the form is sending without any problem but when I tried to add a database for it (cause I want the information to be save at the database at the same time send it) and tried to send it I keep on having this error:
But when I go to the other page it's working properly. I'm not really sure what the problem is cause I'm new with this kind of stuffs, but maybe the problem is related to this class:
public class RegisterRepository
{
//SqlTransaction transaction = null;
private SqlConnection con;
//To Handle connection related activities
private void connection()
{
string constr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString();
con = new SqlConnection(constr);
}
public bool Register(TalentInfo model)
{
connection();
try
{
SqlCommand com = new SqlCommand("SP_INSERT_TALENT_INFO", con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#Talent_Name", model.Talent_Name);
com.Parameters.AddWithValue("#Talent_Email", model.Talent_Email);
com.Parameters.AddWithValue("#Talent_SelfPromotion", model.Talent_SelfPromotion);
con.Open();
int i = com.ExecuteNonQuery();
con.Close();
if (i >= 1)
{
return true;
}
else
{
return false;
}
}
catch
{
return Register(model);
}
finally
{
con.Close();
}
}
}
I tried repairing my IIS 8.0 Express, (SSL Enable = True), and other solutions but it still doesn't work. Please someone help me. Thank you in advance.
The code below serves to change connection string in App.config at runtime, I found it here but this code did not work for me on Visual Studio 2010 and SQL Server 2008, I could not open the connection to the Northwind database.
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Windows.Forms;
using System.Xml;
namespace MyNameSpace
{
public partial class FrmConnectionTest : Form
{
public FrmConnectionTest()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
//Constructing connection string from the inputs
StringBuilder Con = new StringBuilder("Data Source=");
Con.Append(TxtServer.Text);
Con.Append(";Initial Catalog=");
Con.Append(TxtDatabase.Text);
Con.Append(";Integrated Security=SSPI;");
string strCon = Con.ToString();
updateConfigFile(strCon);
//Create new sql connection
SqlConnection Db = new SqlConnection();
//to refresh connection string each time else it will use previous connection string
ConfigurationManager.RefreshSection("connectionStrings");
Db.ConnectionString = ConfigurationManager.ConnectionStrings["con"].ToString();
//To check new connection string is working or not
SqlDataAdapter da = new SqlDataAdapter("select * from employee");
DataTable dt = new DataTable();
da.Fill(dt);
CmbTestValue.DataSource = dt;
CmbTestValue.DisplayMember = "EmployeeID";
}
catch (Exception E)
{
MessageBox.Show(ConfigurationManager.ConnectionStrings["con"].ToString() + ".This is invalid connection", "Incorrect server/Database");
}
}
public void updateConfigFile(string con)
{
//updating config file
XmlDocument XmlDoc = new XmlDocument();
//Loading the Config file
XmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
foreach (XmlElement xElement in XmlDoc.DocumentElement)
{
if (xElement.Name == "connectionStrings")
{
//setting the coonection string
xElement.FirstChild.Attributes[2].Value = con;
}
}
//writing the connection string in config file
XmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);
}
}
}
Using Visual Studio 2010 and SQL Server2008, I got 2 errors for the next line:
SqlDataAdapter da = new SqlDataAdapter("select * from employee");
Error 1 The best overloaded method match for 'System.Data.SqlClient.SqlDataAdapter.SqlDataAdapter(System.Data.SqlClient.SqlCommand)' has some invalid arguments
Error 2 Argument 1: cannot convert from 'string' to 'System.Data.SqlClient.SqlCommand'
Is there any solution to this issue? Thank you.
The error is telling you that you are passing incorrect parameters to your SqlDataAdapter. I think the proper call would be:
SqlDataAdapter da = new SqlDataAdapter("select * from employee", Db);
Edit
It looks like you're creating your connection string from within your program, saving it to your config file, then reading it out of our config file right before you create your SqlDataAdapter. So, when you debug this line:
Db.ConnectionString = ConfigurationManager.ConnectionStrings["con"].ToString();
Double check that Db.ConnectionString actually contains a connection string.
The other thing to do is open up your SQL Server Management Studio and confirm you can connect to the Northwind database from there. Including/alternatively, in Visual Studio, open your "Server Explorer" window and confirm you can create a Data Connection to Northwind by clicking Add Connection and then setting the connection property window to your server and dropping down the combobox to see if it populates with your databases:
Take a look at the available constructors of the SqlDataAdapter class.
There is no constructor overload that accepts just an SQL String.
You need to use one of the other overloads.
For example, there is one that needs an SQL String and a SqlConnection object.
To use it, change your code like this:
SqlDataAdapter da = new SqlDataAdapter("select * from employee", Db);
EDIT:
As BradRem already mentioned in his comment, try a different connection string.
If his example doesn't work for you, you can find more possible examples at http://connectionstrings.com/sql-server-2008.
Do you really have a database called Northwind on your server?
Does the Windows user on your current machine have permissions on the server to access the database? (that's what Integrated Security=SSPI means - your current Windows user is used to access the database!)