Manually Connection between SQL Server and Model - sql-server

I created a empty project in ASP.Net and then I manually add it view,controller and model. Now I want to connect SQL Server to Model class. How can I do it ?

try with this code, this code contain select query for just example
// Is your string connection to your database and server
string connectionString = ""; //connection to your database
//Create a connection to your database
//using bloc , in order to destruct connection object in the end of treatment
using (SqlConnection connection = new SqlConnection(connectionString))
{
//Create object command who contain your query sql, permit you to get data or //insert on update or delete data
using (SqlCommand command= connection.CreateCommand())
{
//for example a query, who select data from table in your databse,
command.CommandText = "SELECT * FROM Table where col = #ParameterTest";
//for exxample a parameter for your query
command.Parameters.Add("#ParameterTest", 123); //your test value
//after create connection you must open this
command.Connection.Open();
//get data in reader, structure for readin datas
var reader = command.ExecuteDataReader();
}
}

Related

How do we extract blob data type column's data from h2 database?

We've deployed nodes and posted a transaction from one node to another using corda and the same got stored in h2 database in "NODE_TRANSACTIONS" table.
TRANSACTION_VALUE column in NODE_TRANSACTIONS table is of BLOB data type.
Please suggest how to extract data from this column in a readable format
We've tried extracting data using resultset.getBinaryStream in java, but not sure of the supported file type in which it needs to be read. Tried with file types image/txt/pdf etc but none of the files were in readable format.
static String url = "jdbc:h2:tcp://localhost:12345/node";
static String username = "sa";
static String password = "";
Class.forName("oracle.h2.Driver");
Connection conn = DriverManager.getConnection(url, username, password);
System.out.println("getting connection: " + conn);
String sql = "SELECT TX_ID, TRANSACTION_VALUE FROM NODE_TRANSACTIONS where rownum<2";
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
InputStream data=rs.getBinaryStream(2);
File file = new File("D:\\blob.txt");
FileOutputStream fos = new FileOutputStream(file);
byte[] buffer = new byte[1];
while (data.read(buffer) > 0) {
fos.write(buffer);
}
fos.close();
}
conn.close();
Also, please suggest any other way to read the column data using h2 database functions (or) oracle functions
I expect the output to be in a readable format
If you're after having state data stored in a readable format in the database following a transaction, the state must implement the QueryableState interface.
See the docs at https://docs.corda.net/api-persistence.html and the example at https://github.com/corda/cordapp-example/blob/release-V4/java-source/src/main/java/com/example/state/IOUState.java

Changing stored procedure so that it will work with Local connection to SQL Server Db (and update a table)

I have the following code and Insert-statement.. and connection.
SqlConnection con = new SqlConnection();
con.ConnectionString = ("Data Source=DESKTOP-PGHMM6M;Initial Catalog=LocalUsers;Integrated Security=True");
con.Open();
string st = "INSERT INTO data(Username, Password, Hash, EncryptedPassword) VALUES (#Username, #Password, #Hash, #EncryptedPassword)";
SqlCommand cmd = new SqlCommand(st, con);
cmd.Parameters.AddWithValue("#Username", Username);
cmd.Parameters.AddWithValue("#Password", textBox2.Text);
cmd.Parameters.AddWithValue("#Hash", savedPasswordHash);
cmd.Parameters.AddWithValue("#EncryptedPassword", FinalEncryptedPass);
cmd.ExecuteNonQuery(); // invalid object name 'data' < where is this object?
con.Close();
When I run the program it returns the following error:
Invalid object name 'data'
I'm not sure what I did to create this situation. I was fulling around with the "stand-alone sql features" in Visual studio 2017, and I'm not sure where to start, to get back on track to use a local SQL Management Server Studio db that I created.
I found a previous question with the following::
Right click the database project --> Properties
Click Debug
Under Target Connection String, click Edit and select the correct database server
Create a new stored procedure
But I'm not sure what any of this is referring to ^.. any pointers?
welcome to stackoverflow.com
it says you do not have a table (in which you are inserting data) name : "data"...
you must have a database name "LocalUsers". in this database,
create a table name : "data" (with given fields) and you are good to go.

Write datatable to SQL Server - add new, update existing, remove missing

I have a SQL Server table that contains three columns:
PositionID, MeasureID, ModifiedDateTime
In my application I load this data into a DataTable and then add and remove rows to/from the DataTable. I would then like to write this back to the database.
The way I was doing it initially: delete all matching records for the PositionID and then loop and insert command with the all the data (or use Bulk Copy).
Is there a better way to do this more simply?
Try this one:
conn.Open();
SqlCommand cmd = new SqlCommand("Truncate Table SQLTableName", conn);
cmd.ExecuteNonQuery();
SqlBulkCopy bulkCopy = new SqlBulkCopy(conn);
bulkCopy.DestinationTableName = "SQLTableName";
bulkCopy.WriteToServer(datatableName);
"conn" is your connection to SQL-server.

connection string without server name

I am developing a c# application with sql server express database that should be run in a local network. I want to make a setup for my project by InstallAware.
I want to know how to set connection string for clients while I don't know the server name, in the other hand I want to connect to database only knowing InstanceName.
ConnectionString = #"Data Source=ServerName\InstanceName;Initial Catalog=Accounting;Persist Security Info=True;User ID=sa;Password=password";
public static string GetServerName()
{
// https://msdn.microsoft.com/en-us/library/a6t1z9x2%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396
DataTable dt = SqlDataSourceEnumerator.Instance.GetDataSources();
DataRow[] dr = dt.Select("InstanceName='myInstanceName'");
if (dr.Length == 0)
return null;
return dr[0]["ServerName"].ToString();
}

Connecting Google App Script to SQL Server on Azure (DBaaS)

I'm trying to connect a Google Sheet to an instance of SQL Server hosted on Azure (DBaaS) using Google App Script. I keep getting an error message indicating that my connection string is invalid despite my numerous attempts at modifying the code. I can connect to this instance of SQL Server on Azure using both Microsoft SQL Server Management Studio and HeidiSQL from my local machine. Note that I have white listed everyIPp address (0.0.0.0 to 255.255.255.255) to make sure that it wasn't a firewall issue preventing me from connecting.
//var conn = Jdbc.getConnection('jdbc:sqlserver:MyDBName.database.windows.net:1433/MyDBName', 'MyDBUserName', 'MyDBPassword');
// SECOND ITERATION OF CONNECTION STRING
//var conn = Jdbc.getConnection('jdbc:sqlserver://MyDBName.database.windows.net:1433;'+ 'databaseName=MyDBName;user=MyDBUserName;password=MyDBPassword;');
// THIRD ITERATION OF CONNECTION STRING
//var conn = Jdbc.getConnection('jdbc:sqlserver://MyDBName.database.windows.net/MyDBName:1433', 'MyDBUserName', 'MyDBPassword');
// FOURTH ITERATION OF CONNECTION STRING
//var conn = Jdbc.getConnection('MyDBName.database.windows.net','MyDBUserName', 'MyDBPassword');
// FIFTH ITERATION OF CONNECTION STRING
//var conn = Jdbc.getConnection('jdbc:sqlserver://MyDBName.database.windows.net', {user:'MyDBUserName', password:'MyDBPassword'});
// SIXTH ITERATION OF CONNECTION STRING
//var conn = Jdbc.getConnection('MyDBName.database.windows.net', {user:'MyDBUserName', password:'MyDBPassword'});
// SEVENTH ITERATION OF CONNECTION STRING
//var conn = Jdbc.getConnection('jdbc:sqlserver://MyDBName.database.windows.net:1433/MyDBName', {user:'MyDBUserName', password:'MyDBPassword'});
// EIGHT ITERATION OF CONNECTION STRING
//https://developers.google.com/apps-script/reference/jdbc/jdbc
//var conn = Jdbc.getConnection('jdbc:sqlserver://MyDBName.database.windows.net/MyDBName:1433', {user:'MyDBUserName', password:'MyDBPassword'});
// NINTH ITERATION OF CONNECTION STRING - Now I'm just throwing anything at the wall and seeing what sticks!
//var conn = Jdbc.getConnection('jdbc:sqlserver://MyDBName.database.windows.net/MyDBName;user=MyDBUserName;password=MyDBPassword');
// TENTH ITERATION OF CONNECTION STRING
//var conn = Jdbc.getConnection('jdbc:mysql://MyDBName.database.windows.net/MyDBName:1433', {user:'MyDBUserName', password:'MyDBPassword'});
// ELEVENTH ITERATION OF CONNECTION STRING
//var conn = Jdbc.getConnection('jdbc:sqlserver://MyDBName.database.windows.net:1433;databaseName=MyDBName','MyDBUserName','MyDBPassword');
//TWELVTH
//var conn = jdbc:sqlserver://MyDBName.database.windows.net;database=MyDBName;user=MyDBUserName;password=MyDBPassword;
// THIRTEENTH
//var conn = Jdbc.getConnection('jdbc:sqlserver://MyDBName.database.windows.net;user=MyDBUserName;password=MyDBPassword;databaseName=MyDBName;');
// FOURTEENTH
//var conn = Jdbc.getConnection("jdbc:sqlserver//MyDBName.database.windows.net:1433;databaseName=MyDBName;user=MyDBUserName;password=MyDBPassword");
// FIFTEENTH
//var conn = Jdbc.getConnection("jdbc:sqlserver://MyDBName.database.windows.net:1433;databaseName=MyDBName","MyDBUserName","MyDBPassword");
// SIXTEENTH
// http://stackoverflow.com/questions/18978380/error-when-connecting-to-mssql-server-with-google-apps-script-via-jdbc?rq=1
//var conn = Jdbc.getConnection("jdbc:sqlserver://NumericalIPAddress:1433;" + "databaseName=MyDBName;user=MyDBUserName;password=MyDBPassword;");
// SEVENTEENTH
// same as above with one less semicolon
//var conn = Jdbc.getConnection("jdbc:sqlserver://NumericalIPAddress:1433;" + "databaseName=MyDBName;user=MyDBUserName;password=MyDBPassword");
//EIGHTEENTH
// http://stackoverflow.com/questions/15440939/querying-sql-server-with-google-apps-script-via-jdbc
var conn = Jdbc.getConnection("jdbc:sqlserver://MyDBName.database.windows.net:1433;databaseName=MyDBName","MyDBUserName","MyDBPassword");
You can find the exact connection string you should use for your database in the portal. Click on the database in the current portal (https://manage.windowsazure.com) and you should see a section that says "Connect to your database" below that there is a link that says "View SQL Database connection strings for ADO .Net, ODBC, PHP, and JDBC.
Alternatively, if you are using the new version of the Azure portal (https://portal.azure.com), you can find the connection strings via Browse All > SQL databases > MyDBName > Show database connection strings.
The example it provides for me looks like:
jdbc:sqlserver://server21.database.windows.net:1433;database=Test;user=myuser#server21;password={your_password_here};encrypt=true;hostNameInCertificate=*.database.windows.net;loginTimeout=30;
I'm trying to connect to an Azure database and found that the JDBC connection string specified in the Azure portal and the sample from Google do not work as-is. The Azure one contains several properties that the script engine says are not supported and the Google one (updated from MySQL) doesn't work. Here's what I got to work:
var user = 'USER#SERVER';
var userPwd = 'PASSWORD';
var database = 'DB_NAME'
var connectionString = 'jdbc:sqlserver://SERVER.database.windows.net:1433;databaseName=' + database;
var conn = Jdbc.getConnection(connectionString , user, userPwd);
NOTE: "database=" is not supported but "databaseName=" is supported. None of the encrypt or certificate tags are supported.
Also, there is a big set of IP ranges you must add to the firewall rules on your server instance. If you use the portal to add these note that you can only make one change to the firewall rules at a time; this means add a range, save, repeat. Don't add all 10 and then get an error when trying to save them (like I did the first time). see: https://developers.google.com/apps-script/guides/jdbc
For your information, the right connection string that works(as at June 5th 2018) to create an ODBC connection between Google Apps Script and a SQL Server DB on Azure DBaaS is as follows:
var conn = Jdbc.getConnection('jdbc:sqlserver://SERVER.database.windows.net:1433;databaseName={yourDatabaseName};user={yourUsername}#{yourServer};password={yourPassword}');

Resources