I'm having a lot of errors can't open connect etc. I use VS 2010 c# wpf
String str;
SqlConnection myConn = new SqlConnection("Server=localhost;Integrated security=SSPI;database=master");
str = " CREATE DATABASE "
+ " ON PRIMARY "
+ " (NAME = " + "MyDatabase_Data" + ", "
+ " FILENAME = '" + "C:\\MyDatabaseData.mdf" + "', "
+ " SIZE = 2MB,"
+ " FILEGROWTH =" + "10%" + ") "
+ " LOG ON (NAME =" + "MyDatabase_Log" + ", "
+ " FILENAME = '" + "C:\\MyDatabaseLog.ldf" + "', "
+ " SIZE = 1MB, "
+ " FILEGROWTH =" + "10%" + ") ";
SqlCommand myCommand = new SqlCommand(str, myConn);
try
{
myConn.Open();
myCommand.ExecuteNonQuery();
MessageBox.Show("DataBase is Created Successfully", "MyProgram", MessageBoxButton.OK, MessageBoxImage.Information);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString(), "MyProgram", MessageBoxButton.OK, MessageBoxImage.Information);
}
finally
{
if (myConn.State == ConnectionState.Open)
{
myConn.Close();
}
}
Add the following references:
c:\Program Files\Microsoft SQL
Server\100\SDK\Assemblies\Microsoft.SqlServer.Smo.dll
C:\Program Files (x86)\Microsoft SQL Server\100\SDK\Assemblies\Microsoft.SqlServer.Management.Sdk.Sfc.dll
c:\Program Files\Microsoft SQL
Server\100\SDK\Assemblies\Microsoft.SqlServer.ConnectionInfo.dll
In App config please inser the following fragment
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0"/>
</startup>
The code:
var myConn = "Server=localhost;Integrated security=SSPI;database=master";
//The CREATE DATABASE statement failed. The primary file must be at least 3 MB to accommodate a copy of the model database.
var command = #"
CREATE DATABASE myDB
ON PRIMARY
(
NAME = MyDatabaseData,
FILENAME = 'C:\Temp\MyDatabaseData.mdf',
SIZE = 3MB,
FILEGROWTH =10%
)
LOG ON
(
NAME =MyDatabaseLog,
FILENAME = 'C:\Temp\MyDatabaseLog.ldf',
SIZE = 1MB,
FILEGROWTH =10%
)";
using (var conn = new SqlConnection(myConn))
{
try
{
var server = new Server(new ServerConnection(conn));
server.ConnectionContext.ExecuteNonQuery(command);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
Related
public static boolean CheckIsDataAlreadyInDBorNot(String TableName,
String dbfield, String fieldValue) {
SQLiteDatabase sqldb = EGLifeStyleApplication.sqLiteDatabase;
String Query = "Select * from " + TableName + " where " + dbfield + " = " + fieldValue;
Cursor cursor = sqldb.rawQuery(Query, null);
if(cursor.getCount() <= 0){
cursor.close();
return false;
}
cursor.close();
return true;
}
How do I accept null values into the SQL Server database with Kotlin? I am trying to make that if the user does not input anything into the column, it will return null instead in the SQL Server. But I failed to do so and a bunch of numbers is saved instead, may I know how can I do it? Below are my codes and the input I got from SQL Server.
For example: 2131231267 and 2131231270 is saved instead of NULL.
fun createGoals()
{
val sqlCon = SQLCon()
checkGoal()
checkTargetAmount()
checkSavedAmount()
checkNote()
if (checkGoal() == true && checkTargetAmount() == true){
Toast.makeText(this, "Creating Goals...", Toast.LENGTH_LONG).show()
connection = sqlCon.connectionClass()!!
if(connection == null)
{
Toast.makeText(this, "Failed to make connection", Toast.LENGTH_LONG).show()
}
else {
try{
val sql :String =
"INSERT INTO Budget(gName,sAmount,Note,tAmount) VALUES ('" + binding.txtGoal.text.toString() + "'" +
",'" + Integer.valueOf(R.id.txtSavedAmount.toString()) + "'" +
",'" + R.id.txtNote.toString()+ "'" +
",'" + Integer.valueOf(binding.txtTargetAmount.text.toString().trim()) + "')"
statement = connection!!.createStatement()
statement!!.executeUpdate(sql)
Toast.makeText(this, "Going In ", Toast.LENGTH_LONG).show()
}
catch (e : Exception){
Log.e("Error", e.message!!)
}
status = true
}
}
}
private fun checkNote() : String?
{
var Note : String? = R.id.txtNote.toString()
if(Note.isNullOrEmpty())
{
Note = " "
}
return Note
}
private fun checkSavedAmount() : String?
{
var savedAmount: String? = R.id.txtSavedAmount.toString()
if(savedAmount.isNullOrEmpty())
{
savedAmount = " "
}
return savedAmount
}
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
MyForm2^ myform2 = gcnew MyForm2();
String^ constring = L"datasource=localhost;port=3306;username=root;password=root";
MySqlConnection^ conDataBase = gcnew MySqlConnection(constring);
MySqlCommand^ cmdDataBase = gcnew MySqlCommand(
"Update librarysystem.bookdetails set isbn = '" + this->textBox1->Text +
"', booktitle = '" + this->textBox2->Text +
"', bookauthor = '" + this->textBox3->Text +
"', bookcategory = '" + this->comboBox1->SelectedItem +
"', bookedition = '" + this->textBox5->Text +
"', booknumofcopies = '" + this->textBox4->Text +
"' where isbn = '" + myform2->listView1->FocusedItem->ListView + "' ;",
conDataBase);
MySqlDataReader^ myReader;
MyForm2^ myform2 = gcnew MyForm2();
...
myform2->listView1->FocusedItem->ListView
There's something wrong with your declaration of MyForm2. Most likely is that you didn't #include "MyForm2.h". You are probably also getting errors about 'MyForm2' : undeclared identifier.
My function: Removes the unit in a specific row of a given Table
private static void removeUnits(String connectionString, String tableName, String columnID, String columnToFix)
{
List<String> rowsToEdit = new List<String>();
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (var command = connection.CreateCommand())
{
command.CommandText = "SELECT " + columnID + "," + columnToFix + " FROM " + tableName;
connection.Open();
using (var reader = command.ExecuteReader())
{
var indexOfR_MEASUREDVALUEID = reader.GetOrdinal(columnID);
var indexOfT_VALUE = reader.GetOrdinal(columnToFix);
while (reader.Read())
{
var t_value = reader.GetValue(indexOfT_VALUE);
var t_id = reader.GetValue(indexOfR_MEASUREDVALUEID);
String newValue = getWithoutUnit(t_value.ToString());
if (newValue != null)
{
String sql = "UPDATE " + tableName + " SET " + columnToFix + "='" +
newValue + "' WHERE " + columnID + "='" + t_id + "';";
rowsToEdit.Add(sql);
}
}
connection.Close();
}
}
Console.WriteLine("start writing " + rowsToEdit.Count + " entries?");
Console.ReadLine();
SqlCommand sqlCmd;
sqlCmd = new SqlCommand("", connection);
sqlCmd.Connection.Open();
foreach (String command in rowsToEdit)
{
sqlCmd.CommandText = command;
sqlCmd.ExecuteNonQuery();
}
}
Console.WriteLine(rowsToEdit.Count + " commands executed");
}
I am using C# in Visual Studio 2010 and SQL-Server 2012.
It works fine, but executing of 200000 lines takes really long.
Is its possible to do this faster?
My suggestion involves looking into parallelism:
Note: The code isn't tested, just typed it out in Notepad++
private static void removeUnits(String connectionString, String tableName, String columnID, String columnToFix)
{
List<new Tuple<object, object>> rowsToEdit = new List<new Tuple<object, object>>();
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (var command = connection.CreateCommand())
{
command.CommandText = "SELECT " + columnID + "," + columnToFix + " FROM " + tableName;
connection.Open();
using (var reader = command.ExecuteReader())
{
var indexOfR_MEASUREDVALUEID = reader.GetOrdinal(columnID);
var indexOfT_VALUE = reader.GetOrdinal(columnToFix);
while (reader.Read())
{
rowsToEdit.Add(new Tuple<object, object>(reader.GetValue(indexOfT_VALUE),reader.GetValue(indexOfR_MEASUREDVALUEID)));
}
connection.Close();
}
}
}
// Use parallelism here
Parallel.Foreach(rowsToEdit, currentRow =>
{
String newValue = getWithoutUnit(currentRow.Value1.ToString());
if (newValue != null)
{
// reopen connection
// use parameters here, and call SP
}
}
Console.WriteLine("start writing " + rowsToEdit.Count + " entries?");
Console.ReadLine();
}
Stored Proc:
Create StoredProcedure MySP
(
#tablename varchar(50),
#columnToFix varchar(50),
#newValue varchar(50),
#columnID varchar(50),
#tID varhcar(varchar(50)
)
As
Begin
Declare #MySQL varchar(500)
Set #MySQL = 'Update ' + #tableName + ' Set ' + #columnToFix + ' = '' + #newValue + ''' + ' Where ' + #columnID + ' = '' + #tID + '''
sp_executesql #MySQL
End
It's important to note that dynamic sql is generally frowned down upon. Here's a link discussing dynamic sql (pros/cons):http://www.sommarskog.se/dynamic_sql.html
Also it's possible you may run into some locking/contention issues b/c you're hitting one table(based on the input parameters of the function).
First try to use Parameters as already mentioned in the comments. Second, use the SqlCommand.Prepare() statement. The actual speed also depends on your machine capacities (HD Write Speed/RAM). Here is the example (you may have to edit the SqlDbTypes according to your Colum Types)
private static void RemoveUnits(string connectionString, string tableName, string columnID, string columnToFix)
{
Dictionary<int, string> rowsToEdit = new Dictionary<int, string>();
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "SELECT " + columnID + "," + columnToFix + " FROM " + tableName;
using (var reader = command.ExecuteReader())
{
var indexOfR_MEASUREDVALUEID = reader.GetOrdinal(columnID);
var indexOfT_VALUE = reader.GetOrdinal(columnToFix);
while (reader.Read())
{
string t_value = reader.GetString(indexOfT_VALUE);
int t_id = reader.GetInt32(indexOfR_MEASUREDVALUEID);
string newValue = getWithoutUnit(t_value);
if (newValue != null)
{
// save values in dictionary
rowsToEdit[t_id] = newValue;
}
}
}
}
Console.WriteLine("start writing " + rowsToEdit.Count + " entries?");
Console.ReadLine();
string updateCmd = "UPDATE " + tableName + " SET " + columnToFix + "= #Value WHERE " + columnID + "= #Key;";
using (SqlTransaction transaction = connection.BeginTransaction())
{
SqlCommand sqlCmd = connection.CreateCommand();
sqlCmd.CommandText = updateCmd;
sqlCmd.Parameters.Add("#Value", System.Data.SqlDbType.NVarChar, -1);
sqlCmd.Parameters.Add("#Key", System.Data.SqlDbType.Int);
// important for performance
sqlCmd.Prepare();
foreach (var update in rowsToEdit)
{
// change values of parameters
sqlCmd.Parameters["#Key"].Value = update.Key;
sqlCmd.Parameters["#Value"].Value = update.Value;
// and execute it
sqlCmd.ExecuteNonQuery();
}
transaction.Commit();
}
}
Console.WriteLine(rowsToEdit.Count + " commands executed");
}
Edit: if getWithoutUnit(string) does something not very complex, you could probably do your operation with a single statement using TSQL, which comes with various string manipulation capabilities. Like UPDATE TableName SET StringColumn = <string manipulation TSQL here>, see http://msdn.microsoft.com/en-us/library/ms181984.aspx
Edit2: added transaction from comment hint (indeed should be faster as well), strongly typed columns
I have a problem that doesn't appear always, but it do it most of the times. In my huge java forecast class I have some ResultSets, and when I execute the routine I get:
com.microsoft.sqlserver.jdbc.SQLServerException: El nombre de columna DistanciaMision no es vßlido.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:170)
at com.microsoft.sqlserver.jdbc.SQLServerResultSet.findColumn(SQLServerResultSet.java:626)
at com.microsoft.sqlserver.jdbc.SQLServerResultSet.getString(SQLServerResultSet.java:2301)
at es.csic.iiia.udt.itim.iInformation.WebData.Forecast.etaMSR(Forecast.java:1109)
at es.csic.iiia.udt.itim.iInformation.WebData.Forecast.phase2(Forecast.java:662)
at es.csic.iiia.udt.itim.iInformation.WebData.Forecast.setData(Forecast.java:166)
at es.csic.iiia.udt.itim.iInformation.WebData.Forecast.main(Forecast.java:81)
at es.csic.iiia.udt.itim.iInformation.WebData.Forecast.execute(Forecast.java:71)
at org.quartz.core.JobRunShell.run(JobRunShell.java:199)
at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:546)
The column exists, so I don't know what is the problem...
The code line is this one:
Float distancia_restante = (float) ( Integer.parseInt(rs.getString("DistanciaMision")) - (myodometer - initialodometer));
The same problem appears on other columns but it usually crash here.
Thank you!
Edit: ok, this is the whole method:
private static void etaMSR() throws Exception, SQLException {
/**
*
* Calculem ETAN MSR - Mision - Seguimiento - Restricciones conductor
*
*
**/
System.out
.print("Get data from iTIM forecast&forecastAUX DDBB ....... ");
myStatement = MSSQLServerAccess.connection();
// Distancia mision, ruta, hora mision anterior, hora
rs = getTable("SELECT dbo.WebForecast.IdConductor, dbo.WebForecast.IdMision, dbo.WebForecast.IdMisionAnterior, dbo.WebForecast.DistanciaMision, "
+ " WebForecast_1.HoraIniMis AS himanterior, dbo.WebForecast.HoraFiMis AS hfmactual, WebForecast_1.Ciudad AS CiudadOrigen,"
+ " dbo.WebForecast.Ciudad AS CiudadDestino, dbo.Distancias.Ruta, dbo.WebForecast.HoraDistancia AS HoraDistancia"
+ " FROM dbo.WebForecast AS WebForecast_1 INNER JOIN"
+ " dbo.Distancias ON WebForecast_1.Ciudad = dbo.Distancias.Origen RIGHT OUTER JOIN"
+ " dbo.WebForecast ON WebForecast_1.IdMision = dbo.WebForecast.IdMisionAnterior AND dbo.Distancias.Destino = dbo.WebForecast.Ciudad"
+ " WHERE (dbo.WebForecast.IdConductor <> '') AND (CONVERT(datetime, '"
+ df.format(fechaDia)
+ "') <= dbo.WebForecast.HoraFiMis) "
+ " AND WebForecast_1.HoraIniMis <= CONVERT(datetime, '"
+ df.format(fechaDia) + "') ");
System.out.println("[ok]");
while (rs.next() && (rs.getString("IdConductor") != "") && org.apache.commons.lang.StringUtils.isNumeric(rs.getString("IdConductor"))) {
int initialodometer = 0;
String start = null;
if (rs.getString("HoraDistancia") != null) {
start = rs.getString("HoraDistancia");
}
if (rs.getString("himanterior") != null) {
start = rs.getString("himanterior");
}
if (start != null) {
ResultSet myrs = null;
Timestamp tobjetivo = rs.getTimestamp("himanterior");
long boundtime = 7200000; // 3600000 = 60m = 1h
Timestamp tini = (Timestamp) rs.getTimestamp("himanterior")
.clone();
Timestamp tfin = (Timestamp) rs.getTimestamp("himanterior")
.clone();
tini.setTime(tini.getTime() - boundtime);
tfin.setTime(tfin.getTime() + boundtime);
int contador = 0;
long bestdiff = 0;
myStatement = MSSQLServerAccess.connection();
myrs = getTable("SELECT DISTINCT Odometer, DT "
+ "FROM DriverEvents "
+ "WHERE (DT BETWEEN CONVERT(datetime, '"
+ df.format(tini) + "') " + "AND CONVERT(datetime, '"
+ df.format(tfin) + "')) " + "AND (CardId = '"
+ Integer.parseInt(rs.getString("IdConductor")) + "')");
int j = 0;
while (!myrs.next() && (j < 20)) {
// En caso de no encontrar en las 2h antes y despues nada:
tini.setTime(tini.getTime() - boundtime);
tfin.setTime(tfin.getTime() + boundtime);
myrs.close();
myStatement = MSSQLServerAccess.connection();
myrs = getTable("SELECT DISTINCT Odometer, DT "
+ "FROM DriverEvents "
+ "WHERE (DT BETWEEN CONVERT(datetime, '"
+ df.format(tini) + "') "
+ "AND CONVERT(datetime, '" + df.format(tfin)
+ "')) " + "AND (CardId = '"
+ Integer.parseInt(rs.getString("IdConductor"))
+ "')");
j++;
}
if (myrs.next()) {
initialodometer = myrs.getInt("Odometer");
bestdiff = Math.abs(tobjetivo.getTime()
- myrs.getTimestamp("DT").getTime());
contador++;
while (myrs.next()) {
long pretendiente = Math.abs(tobjetivo.getTime()
- myrs.getTimestamp("DT").getTime());
if (pretendiente <= bestdiff) {
bestdiff = pretendiente;
initialodometer = myrs.getInt("Odometer");
}
contador++;
}
}
myrs.close();
}
// Get Odometer distance at the moment
if (!rs.getString("IdConductor").isEmpty() && !rs.getString("IdConductor").equals("") ) {
ResultSet myrs = null;
int myodometer = 0;
myStatement = MSSQLServerAccess.connection();
myrs = getTable("SELECT MAX(DT) AS DT, MAX(Odometer) AS Odometer"
+ " FROM dbo.DriverEvents"
+ " WHERE (CardId = '"
+ Integer.parseInt(rs.getString("IdConductor"))
+ "') AND (DT > CONVERT(datetime, '"
+ df.format(fechaDatos) + "')) ");
if (myrs.next()) {
myodometer = myrs.getInt("Odometer");
if (initialodometer == 0)
initialodometer = myodometer;
Float distancia_restante = (float) ( Integer.parseInt(rs.getString("DistanciaMision")) - (myodometer - initialodometer));
if (distancia_restante < 0)
distancia_restante = (float) 0;
Timestamp ETAN = null;
Calendar cal = Calendar.getInstance();
if (rs.getTimestamp("himanterior") != null && rs.getTimestamp("himanterior").toString() != "") {
cal.setTimeInMillis(rs.getTimestamp("himanterior")
.getTime());
if (cal.after(Calendar.getInstance())) {
cal.setTimeInMillis(rs.getTimestamp("himanterior")
.getTime());
}
if (cal.before(Calendar.getInstance())) {
cal = Calendar.getInstance();
}
} else {
if (rs.getTimestamp("HoraDistancia") != null)
cal.setTimeInMillis(rs
.getTimestamp("HoraDistancia").getTime());
}
myStatement = MSSQLServerAccess.connection();
rs2 = getTable("SELECT TOP (100) PERCENT CardId, DT"
+ " FROM dbo.DriverEvents"
+ " GROUP BY CardId, DT"
+ " HAVING (CardId = '"
+ Integer.parseInt(rs.getString("IdConductor"))
+ "') AND (DT > CONVERT(datetime, '"
+ df.format(fechaDatos) + "'))");
if (rs2.next()) {
ETAN = getETAN(rs, distancia_restante, cal);
} else {
ETAN = getETA(rs, distancia_restante, cal, 1);
Statement myStatement2 = MSSQLServerAccess.connection();
myStatement2.executeUpdate("UPDATE WebForecast "
+ "SET ETAmsr = '" + df.format(ETAN)
+ "', KmsDiff = '" + distancia_restante.intValue()
+ "' " + "WHERE IdMision = '"
+ rs.getString("IdMision") + "'");
} else {
}
}
}
rs.close();
}
And the statement, maybe i'm doing something wrong?:
private static Statement conStatement(Properties properties){
String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; // Load the JDBC driver
String dbURL = "jdbc:sqlserver://"
+ properties.getProperty("qualcomm.action.JDBC.MSSQLServerAccess.ddbbserverIP")
+ ";DatabaseName="
+ properties.getProperty("qualcomm.action.JDBC.MSSQLServerAccess.ddbbName")
+ ";SelectMethod=Cursor;"; // Connect to a server and database
String userName = properties.getProperty("qualcomm.action.JDBC.MSSQLServerAccess.userName");
String userPwd = properties.getProperty("qualcomm.action.JDBC.MSSQLServerAccess.userPwd");
Connection dbConn;
try {
Class.forName(driverName);
dbConn = DriverManager.getConnection(dbURL, userName, userPwd);
//log.info("Connection Successful!");
Statement myst = dbConn.createStatement();
return myst;
} catch (Exception e) {
log.error(e);
System.out.println(e);
return null;
}
}
Thanks guys :) Could be something wrong with the statement?
remember that Java is case-sensitive and so can be your table on SQL depending on the way you created them, actually depending on the collation on your DB. If your database is created with a Case Sensitive collation then all object names will be Case Sensitive.
try to check the exact columns name of the column on SQL and access it using [] and the exact case